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
shortanswer.module.ts
// (C) Copyright 2015 Martin Dougiamas // // 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...
@NgModule({ declarations: [ AddonQtypeShortAnswerComponent ], imports: [ IonicModule, TranslateModule.forChild(), CoreDirectivesModule ], providers: [ AddonQtypeShortAnswerHandler ], exports: [ AddonQtypeShortAnswerComponent ], entryCo...
random_line_split
shortanswer.module.ts
// (C) Copyright 2015 Martin Dougiamas // // 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...
{ constructor(questionDelegate: CoreQuestionDelegate, handler: AddonQtypeShortAnswerHandler) { questionDelegate.registerHandler(handler); } }
AddonQtypeShortAnswerModule
identifier_name
microservice.py
""" Agador Metaservice Usage: agador [options] Options: -c --config URI # Service config URI -d --debug # Run in debug mode -h --host HOST # Host IP [default: 0.0.0.0]
import furi from envopt import envopt from flask import Flask from flask import jsonify from . import __version__ APP = Flask("Agador") OPT = envopt(__doc__, env_prefix="MRMET") def config(): """ Helper to get server config. """ try: return dict(furi.map(OPT["--config"])) except AttributeError: ...
-p --port PORT # Port no [default: 8500] """
random_line_split
microservice.py
""" Agador Metaservice Usage: agador [options] Options: -c --config URI # Service config URI -d --debug # Run in debug mode -h --host HOST # Host IP [default: 0.0.0.0] -p --port PORT # Port no [default: 8500] """ import furi from envopt import envopt from f...
(svc): """ Get microservice. """ return jsonify(service=config().get(svc, {})) def runserver(): """ Run microservice. """ # Strip -- from opts opts = dict((key.lstrip("-"), val) for key, val in OPT.iteritems()) opts["port"] = int(opts["port"]) del opts["config"] # Try to load config ...
service
identifier_name
microservice.py
""" Agador Metaservice Usage: agador [options] Options: -c --config URI # Service config URI -d --debug # Run in debug mode -h --host HOST # Host IP [default: 0.0.0.0] -p --port PORT # Port no [default: 8500] """ import furi from envopt import envopt from f...
def runserver(): """ Run microservice. """ # Strip -- from opts opts = dict((key.lstrip("-"), val) for key, val in OPT.iteritems()) opts["port"] = int(opts["port"]) del opts["config"] # Try to load config config() # Start engine! APP.run(**opts)
""" Get microservice. """ return jsonify(service=config().get(svc, {}))
identifier_body
gui.py
#!/usr/bin/env python import os, sys try: from Tkinter import * except: sys.stderr.write('Please install Tkinter!\n\n') sys.exit(1) root = Tk() root.title('Wavelet Demo') wtype = StringVar() wtype.set('b') type_frame = Frame(root,relief=SUNKEN,borderwidth=2) type_frame.pack(side=TOP,fill=X) Label(type_...
cycle = Button(frame,text='Run',background='yellow',command=scons) cycle.pack() root.mainloop()
'Get parameters from GUI and pass them to SCons' os.system ('scons -Q type=%s pclip=%d view' % (wtype.get(),pclip.get()))
identifier_body
gui.py
#!/usr/bin/env python import os, sys try: from Tkinter import * except: sys.stderr.write('Please install Tkinter!\n\n') sys.exit(1) root = Tk() root.title('Wavelet Demo') wtype = StringVar() wtype.set('b') type_frame = Frame(root,relief=SUNKEN,borderwidth=2) type_frame.pack(side=TOP,fill=X) Label(type_...
pclip_frame = Frame(root,relief=SUNKEN,borderwidth=2) pclip_frame.pack(side=TOP,fill=X) pclip = IntVar() pclip.set(50) scale = Scale(pclip_frame,from_=1,to=99,resolution=1,orient=HORIZONTAL, variable=pclip,length=200) scale.pack(side=RIGHT) Label(pclip_frame,text='Threshold\nPercentile').pack(side=R...
rbut = Radiobutton(type_frame,text=types[t],value=t,variable=wtype) rbut.pack(side=LEFT)
conditional_block
gui.py
#!/usr/bin/env python import os, sys try: from Tkinter import * except: sys.stderr.write('Please install Tkinter!\n\n') sys.exit(1) root = Tk() root.title('Wavelet Demo') wtype = StringVar() wtype.set('b') type_frame = Frame(root,relief=SUNKEN,borderwidth=2) type_frame.pack(side=TOP,fill=X) Label(type_...
root.mainloop()
random_line_split
gui.py
#!/usr/bin/env python import os, sys try: from Tkinter import * except: sys.stderr.write('Please install Tkinter!\n\n') sys.exit(1) root = Tk() root.title('Wavelet Demo') wtype = StringVar() wtype.set('b') type_frame = Frame(root,relief=SUNKEN,borderwidth=2) type_frame.pack(side=TOP,fill=X) Label(type_...
(): 'Get parameters from GUI and pass them to SCons' os.system ('scons -Q type=%s pclip=%d view' % (wtype.get(),pclip.get())) cycle = Button(frame,text='Run',background='yellow',command=scons) cycle.pack() root.mainloop()
scons
identifier_name
player.py
# Copyright Vinicius Castanheira (vncastanheira@gmail.com) - 2012 # This program is a part of the Noir Game. # This program is under the Gnu LGPL. from pygame import * from pyganim import * from entity import Entity from bullet import Bullet class Player(Entity): def __init__(self, x, y, images): Entity.__init__(...
self.bulletGroup.add(Bullet(bulletDirection, self.rect.centery, self.facingDirection, ["bullet.png"])) self.bullets -= 1 if event.type == KEYUP and event.key == K_RIGHT: self.goRight = False if event.type == KEYUP and event.key == K_LEFT: self.goLeft = False def update(self): movement = 4 ...
bulletDirection = self.rect.left
conditional_block
player.py
# Copyright Vinicius Castanheira (vncastanheira@gmail.com) - 2012 # This program is a part of the Noir Game. # This program is under the Gnu LGPL. from pygame import * from pyganim import * from entity import Entity from bullet import Bullet class Player(Entity): def __init__(self, x, y, images): Entity.__init__(...
(self, display): if self.alive: self.animation.play() self.animation.blit(display, (self.rect.x,self.rect.y)) if not self.isHidden: self.exclamation.animation.play() self.exclamation.animation.blit(display, (self.rect.centerx - 4, self.rect.top - 20)) else: self.animationDead.play() self.anim...
draw
identifier_name
player.py
# Copyright Vinicius Castanheira (vncastanheira@gmail.com) - 2012 # This program is a part of the Noir Game. # This program is under the Gnu LGPL. from pygame import * from pyganim import * from entity import Entity from bullet import Bullet class Player(Entity): def __init__(self, x, y, images): Entity.__init__(...
self.animationDead = PygAnimation([("player_dead.png", 0.5)]) def events(self, event): if self.alive: if event.type == KEYDOWN and event.key == K_RIGHT: self.goRight = True self.goLeft = False if self.facingDirection == 'LEFT': self.flip() self.facingDirection = 'RIGHT' if event.type =...
random_line_split
player.py
# Copyright Vinicius Castanheira (vncastanheira@gmail.com) - 2012 # This program is a part of the Noir Game. # This program is under the Gnu LGPL. from pygame import * from pyganim import * from entity import Entity from bullet import Bullet class Player(Entity): def __init__(self, x, y, images): Entity.__init__(...
# Another functions def flip(self): self.animation.flip(True, False) def spotlightCollision(self, spolight): if sprite.collide_rect(self, spolight): self.isHidden = False return True else: self.isHidden = True return False def bulletCollision(self, bullet): if sprite.collide_rect(self, bull...
if self.alive: self.animation.play() self.animation.blit(display, (self.rect.x,self.rect.y)) if not self.isHidden: self.exclamation.animation.play() self.exclamation.animation.blit(display, (self.rect.centerx - 4, self.rect.top - 20)) else: self.animationDead.play() self.animationDead.blit(disp...
identifier_body
TodosAppView.js
// All the subviews of a TodosAppView will always have // the same model as the TodosAppView has. // maria.ElementView.subclass(checkit, 'TodosAppView', { properties: { getContainerEl: function() { return this.find('.content'); // child views will be appended to this element }, i...
} } } });
{ childViews[i].setModel(model); }
conditional_block
TodosAppView.js
// All the subviews of a TodosAppView will always have // the same model as the TodosAppView has. // maria.ElementView.subclass(checkit, 'TodosAppView', { properties: { getContainerEl: function() { return this.find('.content'); // child views will be appended to this element }, i...
} } } } });
var childViews = this.childNodes; for (var i = 0, ilen = childViews.length; i < ilen; i++) { childViews[i].setModel(model);
random_line_split
response.rs
/// The profile if requested in the corresponding query. profile: Option<Box<Profile>>, /// The backtrace says where in the query the error occurred. backtrace: Option<Vec<Frame>>, } impl<O> Response<O> { /// Returns the token identifying this `Response`. pub fn token(&self) -> u64 { s...
/// Additional notes which indicate special properties the response has. notes: Option<Vec<Note>>,
random_line_split
response.rs
_reader(&raw_response[..]).unwrap(); response.token = token; Ok(response) } } impl<O: Deserialize> Deserialize for Response<O> { fn deserialize<D: Deserializer>(deserializer: &mut D) -> Result<Response<O>, D::Error> { deserializer.deserialize(ResponseVisitor { data: PhantomData }) }...
from_u64
identifier_name
actions.rs
use chrono::NaiveDateTime; use diesel::{dsl::exists, prelude::*, select}; use regex::Regex; use std::str::FromStr; use url::Url; use crate::{ models::{Mention, NewMention}, DbError, }; pub fn target_exists(url: &Url, conn: &PgConnection) -> Option<(String, i32)> { use crate::schema::articles::dsl::{articl...
( source_url: String, target_url: String, object_type: &str, id: i32, author: String, title: String, conn: &PgConnection, ) -> Result<Mention, DbError> { use crate::schema::mentions; let now = select(diesel::dsl::now).get_result::<NaiveDateTime>(conn)?; let mut data = NewMention...
create_mention
identifier_name
actions.rs
use chrono::NaiveDateTime; use diesel::{dsl::exists, prelude::*, select}; use regex::Regex; use std::str::FromStr; use url::Url; use crate::{ models::{Mention, NewMention}, DbError, }; pub fn target_exists(url: &Url, conn: &PgConnection) -> Option<(String, i32)> { use crate::schema::articles::dsl::{articl...
if rslt.is_none() { return None; } let caps = rslt.unwrap(); let object_type = caps.get(1); let id_str = caps.get(2); if object_type.is_none() || id_str.is_none() { return None; } let object_type = object_type.unwrap().as_str(); let id: Result<i32, _> = FromStr::...
random_line_split
actions.rs
use chrono::NaiveDateTime; use diesel::{dsl::exists, prelude::*, select}; use regex::Regex; use std::str::FromStr; use url::Url; use crate::{ models::{Mention, NewMention}, DbError, }; pub fn target_exists(url: &Url, conn: &PgConnection) -> Option<(String, i32)> { use crate::schema::articles::dsl::{articl...
Some((object_type.to_owned(), id.unwrap())) } pub fn mention_exists(source: &str, target: &str, conn: &PgConnection) -> bool { use crate::schema::mentions::dsl::*; select(exists( mentions.filter(target_url.eq(target)).filter(source_url.eq(source)), )) .get_result(conn) .unwrap_or_els...
{ return None; }
conditional_block
actions.rs
use chrono::NaiveDateTime; use diesel::{dsl::exists, prelude::*, select}; use regex::Regex; use std::str::FromStr; use url::Url; use crate::{ models::{Mention, NewMention}, DbError, }; pub fn target_exists(url: &Url, conn: &PgConnection) -> Option<(String, i32)> { use crate::schema::articles::dsl::{articl...
let id: Result<i32, _> = FromStr::from_str(id_str.unwrap().as_str()); if id.is_err() { return None; } Some((object_type.to_owned(), id.unwrap())) } pub fn mention_exists(source: &str, target: &str, conn: &PgConnection) -> bool { use crate::schema::mentions::dsl::*; select(exists( ...
{ let path = url.path(); let re = Regex::new(r"^/([^/]+)/(\d+)$").unwrap(); let rslt = re.captures(path); if rslt.is_none() { return None; } let caps = rslt.unwrap(); let object_type = caps.get(1); let id_str = caps.get(2); if object_type.is_none() || id_str.is_none() { ...
identifier_body
dialogue.py
# This stores all the dialogue related stuff import screen class Dialogue(object): """Stores the dialogue tree for an individual NPC""" def __init__(self, npc): super(Dialogue, self).__init__() self.npc = npc self.game = npc.game self.root = None self.currentNode = None def setRootNode(self...
else: availableChoices.append((choice, child)) npcName = None if self.game.player.notebook.isNpcKnown(self.npc): npcName = self.npc.firstName + " " + self.npc.lastName choiceTexts = [choice.choiceText for (choice, child) in availableChoices] screen.printDialogueChoic...
availableChoices.append((choice, child))
conditional_block
dialogue.py
# This stores all the dialogue related stuff import screen class Dialogue(object): """Stores the dialogue tree for an individual NPC""" def __init__(self, npc): super(Dialogue, self).__init__() self.npc = npc self.game = npc.game self.root = None self.currentNode = None def setRootNode(self...
def beginConversation(self): self.resetCurrentNode() self.runNextNode() def runNextNode(self): if self.currentNode is None: return # Grab all the DialogueChoices that should be shown availableChoices = [] for (choice, predicate, child) in self.currentNode.choices: ...
self.currentNode = self.root
identifier_body
dialogue.py
# This stores all the dialogue related stuff import screen class Dialogue(object): """Stores the dialogue tree for an individual NPC""" def __init__(self, npc): super(Dialogue, self).__init__() self.npc = npc self.game = npc.game self.root = None self.currentNode = None def setRootNode(self...
def callResponseFunction(self, npcArgument, response): if responseFunction is not None: self.responseFunction(npcArgument, response)
self.choiceText = choiceText self.response = response self.responseFunction = responseFunction
random_line_split
dialogue.py
# This stores all the dialogue related stuff import screen class Dialogue(object): """Stores the dialogue tree for an individual NPC""" def __init__(self, npc): super(Dialogue, self).__init__() self.npc = npc self.game = npc.game self.root = None self.currentNode = None def setRootNode(self...
(self, choiceText, response, responseFunction=None): super(DialogueChoice, self).__init__() self.choiceText = choiceText self.response = response self.responseFunction = responseFunction def callResponseFunction(self, npcArgument, response): if responseFunction is not None: self.responseFun...
__init__
identifier_name
plot_conv.py
#!/usr/bin/env python3 import matplotlib.pyplot as plt from math import sqrt from math import log dx = [1/sqrt(16), 1/sqrt(64), 1/sqrt(256), 1/sqrt(1024)] dx_tri = [1/sqrt(32), 1/sqrt(128), 1/sqrt(512), 1/sqrt(2048)] dx_pert = [0.0270466, 0.0134827, 0.00680914, 0.00367054]
rl2_euler = [0.00059068, 0.000113051, 2.26156e-05, 5.11884e-06] rl2_euler_tri = [0.00101603, 0.000277795, 6.37774e-05, 1.4947e-05] rl2_euler_tri_pert = [0.00053851, 0.000121805, 2.67446e-05, 4.97857e-05] rl2_euler_tri_limited = [0.00234712, 0.000548344, 0.000139978, 3.56414e-05] rl2_euler_lp_tri_limited = [0.00242227,...
dx_fp = [0.122799, 0.081584, 0.0445639, 0.0225922, 0.0113763] fp_actual = 0.0441995
random_line_split
createLoadBalancer.controller.spec.js
'use strict'; describe('Controller: azureCreateLoadBalancerCtrl', function () { // load the controller's module beforeEach( window.module( require('./createLoadBalancer.controller') ) ); // Initialize the controller and a mock scope beforeEach(window.inject(function ($controller, $rootScope) ...
loadBalancer.listeners = [{externalProtocol: 'HTTP'}]; loadBalancer.listeners.push({ externalProtocol: 'HTTPS' }); expect(this.ctrl.showSslCertificateIdField()).toBe(true); loadBalancer.listeners = [ { externalProtocol: 'HTTPS' }, { externalProtocol: 'HTTPS' }]; expect(this.ctrl.showSslCertificateI...
expect(this.ctrl.showSslCertificateIdField()).toBe(true);
random_line_split
icmp.rs
use core::mem::size_of; use core::option::Option; use common::debug::*; use common::vec::*; use network::common::*; #[derive(Copy, Clone)] #[repr(packed)] pub struct ICMPHeader { pub _type: u8, pub code: u8, pub checksum: Checksum, pub data: [u8; 4] } pub struct ICMP { pub header: ICMPHeader, ...
}
{ d("ICMP "); dbh(self.header._type); d(" code "); dbh(self.header.code); d(" data "); dd(self.data.len()); }
identifier_body
icmp.rs
use core::mem::size_of; use core::option::Option; use common::debug::*; use common::vec::*; use network::common::*; #[derive(Copy, Clone)] #[repr(packed)] pub struct ICMPHeader { pub _type: u8, pub code: u8, pub checksum: Checksum, pub data: [u8; 4] } pub struct ICMP { pub header: ICMPHeader, ...
unsafe { return Option::Some(ICMP { header: *(bytes.as_ptr() as *const ICMPHeader), data: bytes.sub(size_of::<ICMPHeader>(), bytes.len() - size_of::<ICMPHeader>()) }); } } return Option::None; } } impl T...
impl FromBytes for ICMP { fn from_bytes(bytes: Vec<u8>) -> Option<ICMP> { if bytes.len() >= size_of::<ICMPHeader>() {
random_line_split
icmp.rs
use core::mem::size_of; use core::option::Option; use common::debug::*; use common::vec::*; use network::common::*; #[derive(Copy, Clone)] #[repr(packed)] pub struct ICMPHeader { pub _type: u8, pub code: u8, pub checksum: Checksum, pub data: [u8; 4] } pub struct ICMP { pub header: ICMPHeader, ...
(&self) -> Vec<u8> { unsafe{ let header_ptr: *const ICMPHeader = &self.header; let mut ret = Vec::from_raw_buf(header_ptr as *const u8, size_of::<ICMPHeader>()); ret.push_all(&self.data); return ret; } } } impl ICMP { pub fn d(&self){ d("I...
to_bytes
identifier_name
icmp.rs
use core::mem::size_of; use core::option::Option; use common::debug::*; use common::vec::*; use network::common::*; #[derive(Copy, Clone)] #[repr(packed)] pub struct ICMPHeader { pub _type: u8, pub code: u8, pub checksum: Checksum, pub data: [u8; 4] } pub struct ICMP { pub header: ICMPHeader, ...
return Option::None; } } impl ToBytes for ICMP { fn to_bytes(&self) -> Vec<u8> { unsafe{ let header_ptr: *const ICMPHeader = &self.header; let mut ret = Vec::from_raw_buf(header_ptr as *const u8, size_of::<ICMPHeader>()); ret.push_all(&self.data); ...
{ unsafe { return Option::Some(ICMP { header: *(bytes.as_ptr() as *const ICMPHeader), data: bytes.sub(size_of::<ICMPHeader>(), bytes.len() - size_of::<ICMPHeader>()) }); } }
conditional_block
20161005182611-createprocedures.js
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.createTable('users', { id: Sequelize.INTEGER }); */ return queryInterface.createTable( ...
defaultValue: Sequelize.NOW }, updatedAt: { type: Sequelize.DATE, defaultValue: Sequelize.NOW } } ); }, down: function (queryInterface, Sequelize) { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. ...
createdAt: { type: Sequelize.DATE,
random_line_split
probebus.py
___________________________________________________________________________ # # Copyright (C) 2004-2007 # Chair of Communication Networks (ComNets) # Kopernikusstr. 16, D-52074 Aachen, Germany # phone: ++49-241-80-27910, # fax: ++49-241-80-22242 # email: info@openwns.org # www: http://www.openwns.org # ________________...
class TabPar: """ Helper Class to configure the TableProbeBus. Configure one of these for each dimension of your table. Parameters: idName: the name in the IDregistry/Context under which the value for this axis should be searched minimum: min value of the axis maximum: max va...
self.appendFlag = statEvalConfig.appendFlag
conditional_block
probebus.py
___________________________________________________________________________ # # Copyright (C) 2004-2007 # Chair of Communication Networks (ComNets) # Kopernikusstr. 16, D-52074 Aachen, Germany # phone: ++49-241-80-27910, # fax: ++49-241-80-22242 # email: info@openwns.org # www: http://www.openwns.org # ________________...
class ContextFilterProbeBus(ProbeBus): nameInFactory = "ContextFilterProbeBus" idName = None idValues = None def __init__(self, _idName, _idValues, _outputName = None): ProbeBus.__init__(self) self.idName = _idName self.idValues = _idValu...
self.valuePrecision = valuePrecision self.name = name self.description = desc self.contextKeys = contextKeys
random_line_split
probebus.py
___________ # # Copyright (C) 2004-2007 # Chair of Communication Networks (ComNets) # Kopernikusstr. 16, D-52074 Aachen, Germany # phone: ++49-241-80-27910, # fax: ++49-241-80-22242 # email: info@openwns.org # www: http://www.openwns.org # _____________________________________________________________________________ # ...
(self, settlingTime): ProbeBus.__init__(self) self.settlingTime = settlingTime class LoggingProbeBus(ProbeBus): """ The LoggingProbeBus always accepts and logs the message to the logging subsystem. """ nameInFactory = "LoggingProbeBus" def __init__(self,...
__init__
identifier_name
probebus.py
___________________________________________________________________________ # # Copyright (C) 2004-2007 # Chair of Communication Networks (ComNets) # Kopernikusstr. 16, D-52074 Aachen, Germany # phone: ++49-241-80-27910, # fax: ++49-241-80-22242 # email: info@openwns.org # www: http://www.openwns.org # ________________...
class ContextFilterProbeBus(ProbeBus): nameInFactory = "ContextFilterProbeBus" idName = None idValues = None def __init__(self, _idName, _idValues, _outputName = None): ProbeBus.__init__(self) self.idName = _idName self.idValues = _idVal...
ProbeBus.__init__(self) self.outputFilename = outputFilename self.format = format self.timePrecision = timePrecision self.valuePrecision = valuePrecision self.name = name self.description = desc self.contextKeys = contextKeys
identifier_body
make-l1profile.py
#!/usr/bin/env python # Hua Shao <hua.shao@mediatek.com> import sys import re import random l1conf = [] def parseconfig(conf): global l1conf l1conf.extend([[],[],[]]) with open(conf, "r") as fp: for line in fp: if line.startswith("CONFIG_first_card_"): kv = line.split("=") l1conf[0].append((kv[0][l...
# make sure these configs are unique for name in ["main_ifname", "ext_ifname", "wds_ifname", "apcli_name", "mesh_ifname", "nvram_zone", "profile_path"]: if1 = d1.get(name, random.random()) if2 = d2.get(name, random.random()) if3 = d3.get(name, random.random()) assert len(set([if1, if2, if3])) == 3...
for k,v in dx.items(): assert v
conditional_block
make-l1profile.py
#!/usr/bin/env python # Hua Shao <hua.shao@mediatek.com> import sys import re import random l1conf = [] def parseconfig(conf):
def validate(): global l1conf d1 = dict(l1conf[0]) if len(l1conf) > 0 else {} d2 = dict(l1conf[1]) if len(l1conf) > 1 else {} d3 = dict(l1conf[2]) if len(l1conf) > 2 else {} # make sure no empty value for dx in [d1,d2,d3]: for k,v in dx.items(): assert v # make sure these configs are unique for name ...
global l1conf l1conf.extend([[],[],[]]) with open(conf, "r") as fp: for line in fp: if line.startswith("CONFIG_first_card_"): kv = line.split("=") l1conf[0].append((kv[0][len("CONFIG_first_card_"):], kv[1].strip("\"\'\r\n\t"))) elif line.startswith("CONFIG_second_card_"): kv = line.split("=") ...
identifier_body
make-l1profile.py
#!/usr/bin/env python # Hua Shao <hua.shao@mediatek.com> import sys import re import random l1conf = [] def
(conf): global l1conf l1conf.extend([[],[],[]]) with open(conf, "r") as fp: for line in fp: if line.startswith("CONFIG_first_card_"): kv = line.split("=") l1conf[0].append((kv[0][len("CONFIG_first_card_"):], kv[1].strip("\"\'\r\n\t"))) elif line.startswith("CONFIG_second_card_"): kv = line.split...
parseconfig
identifier_name
make-l1profile.py
#!/usr/bin/env python # Hua Shao <hua.shao@mediatek.com> import sys import re import random l1conf = [] def parseconfig(conf): global l1conf l1conf.extend([[],[],[]]) with open(conf, "r") as fp: for line in fp: if line.startswith("CONFIG_first_card_"): kv = line.split("=") l1conf[0].append((kv[0][l...
def validate(): global l1conf d1 = dict(l1conf[0]) if len(l1conf) > 0 else {} d2 = dict(l1conf[1]) if len(l1conf) > 1 else {} d3 = dict(l1conf[2]) if len(l1conf) > 2 else {} # make sure no empty value for dx in [d1,d2,d3]: for k,v in dx.items(): assert v # make sure these configs are unique for name in...
random_line_split
loli_GUI.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import kivy from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.image import Image from kivy.uix.button import Button kivy.require('1.7.3') text ="" class ShowLogo(Im...
# self.add_widget(self.printbutton) #def callback(self,evt=None): # return self.add_widget(Label(text=self.text_input.text)) class AppMain(App): def build(self): img = Image(source="res/wikipe-tan.png") return GetInfo() AppMain().run()
def __init__(self,**kwargs): super(GetInfo, self).__init__(**kwargs) self.cols = 2 self.text=text self.add_widget(Label(text='Gelbooru limit')) self.limit = TextInput(text="100",multiline=False) self.add_widget(self.limit) def on_text(instance,value): ...
identifier_body
loli_GUI.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import kivy from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.image import Image from kivy.uix.button import Button kivy.require('1.7.3') text ="" class ShowLogo(Im...
# self.printbutton = Button(text='Print') # self.printbutton.bind(on_press=self.callback) # self.add_widget(self.printbutton) #def callback(self,evt=None): # return self.add_widget(Label(text=self.text_input.text)) class AppMain(App): def build(self): img = Image(source="res/wikipe-...
a = int(outnumb)
conditional_block
loli_GUI.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import kivy from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.image import Image from kivy.uix.button import Button kivy.require('1.7.3') text ="" class ShowLogo(Im...
(self,**kwargs): super(Image, self).__init__(**kwargs) class GetInfo(GridLayout): def __init__(self,**kwargs): super(GetInfo, self).__init__(**kwargs) self.cols = 2 self.text=text self.add_widget(Label(text='Gelbooru limit')) self.limit = TextInput(text="100",multi...
__init__
identifier_name
loli_GUI.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import kivy from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.image import Image from kivy.uix.button import Button kivy.require('1.7.3') text ="" class ShowLogo(Im...
print('user pressed enter in: ',instance) if self.limit.bind(on_text_validate=on_enter): a = int(outnumb) # self.printbutton = Button(text='Print') # self.printbutton.bind(on_press=self.callback) # self.add_widget(self.printbutton) #def callback(self,evt=None): # r...
def on_text(instance,value): print('widget: ',instance,' - val: ',value) def on_enter(instance,value):
random_line_split
error.rs
//! The module defining custom leveldb error type. use libc::{c_void, free}; use std; /// A leveldb error, just containing the error string /// provided by leveldb. #[derive(Debug)] pub struct Error { message: String, } impl Error { /// create a new Error, using the String provided pub fn new(message: St...
} impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "LevelDB error: {}", self.message) } } impl std::error::Error for Error { fn description(&self) -> &str { &self.message } fn cause(&self) -> Option<&std::error::Error> {...
{ use std::str::from_utf8; use std::ffi::CStr; let err_string = unsafe { from_utf8(CStr::from_ptr(message).to_bytes()).unwrap().to_string() }; unsafe { free(message as *mut c_void) }; Error::new(err_string) }
identifier_body
error.rs
//! The module defining custom leveldb error type. use libc::{c_void, free}; use std; /// A leveldb error, just containing the error string /// provided by leveldb. #[derive(Debug)] pub struct Error { message: String, } impl Error { /// create a new Error, using the String provided pub fn new(message: St...
(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "LevelDB error: {}", self.message) } } impl std::error::Error for Error { fn description(&self) -> &str { &self.message } fn cause(&self) -> Option<&std::error::Error> { None } }
fmt
identifier_name
error.rs
//! The module defining custom leveldb error type. use libc::{c_void, free}; use std; /// A leveldb error, just containing the error string /// provided by leveldb. #[derive(Debug)] pub struct Error { message: String, } impl Error { /// create a new Error, using the String provided pub fn new(message: St...
impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "LevelDB error: {}", self.message) } } impl std::error::Error for Error { fn description(&self) -> &str { &self.message } fn cause(&self) -> Option<&std::error::Error> { ...
Error::new(err_string) } }
random_line_split
process-status-inherits-stdin.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let mut s = String::new(); io::stdin().read_line(&mut s).unwrap(); assert_eq!(s, "foo\n"); } } }
{ let mut args = env::args(); let me = args.next().unwrap(); let arg = args.next(); match arg.as_ref().map(|s| &s[..]) { None => { let mut s = Command::new(&me) .arg("a1") .stdin(Stdio::piped()) ...
identifier_body
process-status-inherits-stdin.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let mut args = env::args(); let me = args.next().unwrap(); let arg = args.next(); match arg.as_ref().map(|s| &s[..]) { None => { let mut s = Command::new(&me) .arg("a1") .stdin(Stdio::piped()) ...
main
identifier_name
process-status-inherits-stdin.rs
// Copyright 2016 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 ...
Some(..) => { let mut s = String::new(); io::stdin().read_line(&mut s).unwrap(); assert_eq!(s, "foo\n"); } } }
{ let s = Command::new(&me).arg("a2").status().unwrap(); assert!(s.success()); }
conditional_block
process-status-inherits-stdin.rs
// Copyright 2016 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. // run-pass // igno...
// http://rust-lang.org/COPYRIGHT. //
random_line_split
tokens.rs
use std::collections::HashMap; #[allow(dead_code)] #[derive(PartialEq, Eq, Debug, Clone, Hash)] pub enum Keyword { AND, BREAK, DO, ELSE, ELSEIF, END, FALSE, FOR, FUNCTION, GOTO, IF, IN, LOCAL, NIL, NOT, OR, REPEAT, RETURN, THEN, TRUE, ...
TokenType::Keyword(ref keyword) => Some(keyword.clone()), _ => None, } } } impl Into<TokenType> for Token { fn into(self) -> TokenType { self.token.clone() } }
_ => None, } } pub fn keyword(&self) -> Option<Keyword> { match self.token {
identifier_body
tokens.rs
use std::collections::HashMap; #[allow(dead_code)] #[derive(PartialEq, Eq, Debug, Clone, Hash)] pub enum Keyword { AND, BREAK, DO, ELSE, ELSEIF, END, FALSE, FOR, FUNCTION, GOTO, IF, IN, LOCAL, NIL, NOT, OR, REPEAT, RETURN, THEN, TRUE, ...
("break", Keyword::BREAK), ("do", Keyword::DO), ("else", Keyword::ELSE), ("elseif", Keyword::ELSEIF), ("end", Keyword::END), ("false", Keyword::FALSE), ("for", Keyword::FOR), ("function", Keyword::FUNCTION), ("goto", Keyword::GOTO), ("if", Ke...
yword::AND),
identifier_name
tokens.rs
use std::collections::HashMap; #[allow(dead_code)] #[derive(PartialEq, Eq, Debug, Clone, Hash)] pub enum Keyword { AND, BREAK, DO, ELSE, ELSEIF, END, FALSE, FOR, FUNCTION, GOTO, IF, IN, LOCAL, NIL, NOT, OR, REPEAT, RETURN, THEN, TRUE, ...
("[", Keyword::LSBRACKET), ("]", Keyword::RSBRACKET), ("{", Keyword::LCBRACKET), ("}", Keyword::RCBRACKET), ("::", Keyword::PATH), (";", Keyword::SEMICOLONS), (":", Keyword::COLONS), (",", Keyword::COMMA), (".", Keyword::DOT), ("..", Keywor...
("(", Keyword::LBRACE), (")", Keyword::RBRACE),
random_line_split
fns.rs
} unsafe { globals.Vcurrent_load_list = ((Qprovide, feature), globals.Vcurrent_load_list).into(); } // Run any load-hooks for this file. unsafe { if let Some((_, d)) = assq(feature.into(), globals.Vafter_load_alist).into() { Fmapc(Qfuncall, d); } } feature...
mapcar1(leni, ptr::null_mut(), function, sequence); sequence } /* List of features currently being require'd, innermost first. */ declare_GC_protected_static!(require_nesting_list, Qnil); unsafe extern "C" fn require_unwind(old_value: LispObject) { require_nesting_list = old_value; } /// If feature FE...
{ wrong_type!(Qlistp, sequence); }
conditional_block
fns.rs
quote ARG) #[lisp_fn(unevalled = "true")] pub fn quote(args: LispCons) -> LispObject { if args.cdr().is_not_nil() { wrong_number_of_arguments!(Qquote, args.length()); } args.car() } /// Apply FUNCTION to each element of SEQUENCE, and make a list of the /// results. The result is a list just as lo...
{ o1.equal_no_quit(o2) }
identifier_body
fns.rs
&rest SEQUENCES) #[lisp_fn] pub fn append(args: &mut [LispObject]) -> LispObject { unsafe { lisp_concat( args.len() as isize, args.as_mut_ptr() as *mut LispObject, Lisp_Type::Lisp_Cons, true, ) } } /// Concatenate all the arguments and make the r...
random_line_split
fns.rs
); } unsafe { globals.Vcurrent_load_list = ((Qprovide, feature), globals.Vcurrent_load_list).into(); } // Run any load-hooks for this file. unsafe { if let Some((_, d)) = assq(feature.into(), globals.Vafter_load_alist).into() { Fmapc(Qfuncall, d); } } feat...
(args: &mut [LispObject]) -> LispObject { unsafe { lisp_concat( args.len() as isize, args.as_mut_ptr() as *mut LispObject, Lisp_Type::Lisp_String, false, ) } } /// Return the reversed copy of list, vector, or string SEQ. /// See also the function ...
concat
identifier_name
build.rs
extern crate build_utils; extern crate protoc_grpcio; use std::fs::File; use std::io::Write; use std::path::PathBuf; use build_utils::BuildRoot; fn main()
"google/rpc/status.proto", "google/longrunning/operations.proto", "google/protobuf/empty.proto", ], &[ thirdpartyprotobuf.join("googleapis"), thirdpartyprotobuf.join("standard"), thirdpartyprotobuf.join("rust-protobuf"), ], &gen_dir, ).expect("Failed to compile prot...
{ let build_root = BuildRoot::find().unwrap(); let thirdpartyprotobuf = build_root.join("3rdparty/protobuf"); println!( "cargo:rerun-if-changed={}", thirdpartyprotobuf.to_str().unwrap() ); let gen_dir = PathBuf::from("src/gen"); // Re-gen if, say, someone does a git clean on the gen dir but not th...
identifier_body
build.rs
extern crate build_utils; extern crate protoc_grpcio; use std::fs::File; use std::io::Write; use std::path::PathBuf; use build_utils::BuildRoot; fn main() { let build_root = BuildRoot::find().unwrap(); let thirdpartyprotobuf = build_root.join("3rdparty/protobuf"); println!( "cargo:rerun-if-changed={}", ...
.filter_map(|d| { let dirent = d.unwrap(); let file_name = dirent.file_name().into_string().unwrap(); match file_name.trim_right_matches(".rs") { "mod" | ".gitignore" => None, module_name => Some(format!("pub mod {};", module_name)), } }) .collect::<Vec<_>>(); pub_m...
let listing = gen_dir.read_dir().unwrap(); let mut pub_mod_stmts = listing
random_line_split
build.rs
extern crate build_utils; extern crate protoc_grpcio; use std::fs::File; use std::io::Write; use std::path::PathBuf; use build_utils::BuildRoot; fn
() { let build_root = BuildRoot::find().unwrap(); let thirdpartyprotobuf = build_root.join("3rdparty/protobuf"); println!( "cargo:rerun-if-changed={}", thirdpartyprotobuf.to_str().unwrap() ); let gen_dir = PathBuf::from("src/gen"); // Re-gen if, say, someone does a git clean on the gen dir but not...
main
identifier_name
main.rs
extern crate rusty_machine as rm; extern crate rand; use rm::linalg::{Matrix, BaseMatrix}; use rand::{Rng, ThreadRng}; use std::collections::HashMap; fn generate_arm(content_id: &usize, arms: &HashMap<usize, Arm>, feature_dim: &usize) -> Arm { let arm: Arm; if !arms.contains_key(content_id) { arm = A...
struct Rulet{ rng: ThreadRng, } impl Rulet{ fn new() -> Rulet { Rulet{ rng: rand::thread_rng(), } } fn generate_features(&mut self, viewer: &Viewer) -> Matrix<f64> { let features = Some(&viewer.gender) .and_then(|gender| if gender=="man" ...
if &self.gender=="man" { // Men are easy to click on ads with id 5 or less if *content_id < 6 { return Some(self.rng.next_f32()).and_then(|n| if n>0.3 {Some(true)} else {Some(false)}).unwrap(); } else{ return Some(self.rng.next_f32()).and_then(|n...
identifier_body
main.rs
extern crate rusty_machine as rm; extern crate rand; use rm::linalg::{Matrix, BaseMatrix}; use rand::{Rng, ThreadRng}; use std::collections::HashMap; fn generate_arm(content_id: &usize, arms: &HashMap<usize, Arm>, feature_dim: &usize) -> Arm { let arm: Arm; if !arms.contains_key(content_id) { arm = A...
} } fn main() { /*Context is for men and women only Men are easy to click on ads with id 5 or less Women are easy to click on ads with id 6 or higher */ let feature_dim = 2; let num_of_views = 10000; let mut rulet = Rulet::new(); let mut content_id: usize; let mut features: Matri...
return "women".to_string(); }
conditional_block
main.rs
extern crate rusty_machine as rm; extern crate rand; use rm::linalg::{Matrix, BaseMatrix}; use rand::{Rng, ThreadRng}; use std::collections::HashMap; fn generate_arm(content_id: &usize, arms: &HashMap<usize, Arm>, feature_dim: &usize) -> Arm { let arm: Arm; if !arms.contains_key(content_id) { arm = A...
let theta = &one_div_cov.elemul(&self.norm_mean); // Again, the inverse matrix of the covariance matrix // is ​​computed by taking reciprocal let mut tmp: f64 = ((features.elemul(&one_div_cov))*features.transpose()).data()[0]; tmp = &tmp.sqrt()*&self.alpha; (theta*feature...
self.cov_matrix.cols(), one_div_cov_vec); // Since the covariance matrix preserves only the diagonal components, // it suffices to take the inverse matrix
random_line_split
main.rs
extern crate rusty_machine as rm; extern crate rand; use rm::linalg::{Matrix, BaseMatrix}; use rand::{Rng, ThreadRng}; use std::collections::HashMap; fn generate_arm(content_id: &usize, arms: &HashMap<usize, Arm>, feature_dim: &usize) -> Arm { let arm: Arm; if !arms.contains_key(content_id) { arm = A...
rng: ThreadRng, } impl Rulet{ fn new() -> Rulet { Rulet{ rng: rand::thread_rng(), } } fn generate_features(&mut self, viewer: &Viewer) -> Matrix<f64> { let features = Some(&viewer.gender) .and_then(|gender| if gender=="man" {Some(Matrix::ne...
t{
identifier_name
easyenter_page.js
/** # Mantis Plugin "EasyEnter" # Copyright (C) 2015 Frithjof Gnas - fg@prae-sensation.de # # Javascript functions and calls to slim down the bug-report-form on the # configured base of include_fields, field_values etc.. # # Disclaimer & License: # This plugin - EasyEnter - is distributed in the hope that it wi...
.not( '[type="button"][type="submit"][type="reset"]' ) .each(function( ) { showhide_input_field_row( jQuery( this ).attr( 'name' ), 0 ); }); //Special fields/rows to hide... if ( easyenter_config.hasOwnProperty( 'exclude_fields' ) ) { for( i = 0; i < easyenter_config.exclude_fields.length; i++ ) { if( ...
random_line_split
easyenter_page.js
/** # Mantis Plugin "EasyEnter" # Copyright (C) 2015 Frithjof Gnas - fg@prae-sensation.de # # Javascript functions and calls to slim down the bug-report-form on the # configured base of include_fields, field_values etc.. # # Disclaimer & License: # This plugin - EasyEnter - is distributed in the hope that it wi...
( ) { jQuery( 'span.required').hide(); }
hide_mandatory_asterisks
identifier_name
easyenter_page.js
/** # Mantis Plugin "EasyEnter" # Copyright (C) 2015 Frithjof Gnas - fg@prae-sensation.de # # Javascript functions and calls to slim down the bug-report-form on the # configured base of include_fields, field_values etc.. # # Disclaimer & License: # This plugin - EasyEnter - is distributed in the hope that it wi...
/** * Hides the row for entering a custom profile, this is not covered by * hide_all_fields_... because in the corresponding row is no input */ function hide_custom_profile_row( ) { jQuery( '#profile_closed' ).parent( 'td' ).parent( 'tr').hide(); } /** * Hide all elements with CSS-class "required" which means...
{ var field = jQuery( '[name="' + field_name + '"]' ); if ( field.length < 1 ) { return; } if( showrow === 1) { field.parents( 'tr' ).show( ); } else { field.parents( 'tr' ).hide( ); } }
identifier_body
easyenter_page.js
/** # Mantis Plugin "EasyEnter" # Copyright (C) 2015 Frithjof Gnas - fg@prae-sensation.de # # Javascript functions and calls to slim down the bug-report-form on the # configured base of include_fields, field_values etc.. # # Disclaimer & License: # This plugin - EasyEnter - is distributed in the hope that it wi...
} /** * Hides the row for entering a custom profile, this is not covered by * hide_all_fields_... because in the corresponding row is no input */ function hide_custom_profile_row( ) { jQuery( '#profile_closed' ).parent( 'td' ).parent( 'tr').hide(); } /** * Hide all elements with CSS-class "required" which mea...
{ field.parents( 'tr' ).hide( ); }
conditional_block
errors.js
var Plugin = require('nokomis/plugin') var Domain = require('domain') var ErrorPage = require('error-page') var _ = require('underscore') module.exports = Plugin.extend({ initialize: function(config) { this.config = config || {} }, run: function(instance, callback) { var req = instance.req var re...
/** * Handle all response errors * * @param {Object} req * @param {Object} res * @param {Object} data * @param {String} template * @api private */ function handleError(req, res, data, template) { req.log.error('Responding with error', data) var config = this.config || {} if (config.NODE_ENV != 'develo...
{ return handleError.call(this, req, res, data, 'errors/500') }
identifier_body
errors.js
var Plugin = require('nokomis/plugin') var Domain = require('domain') var ErrorPage = require('error-page') var _ = require('underscore') module.exports = Plugin.extend({ initialize: function(config) { this.config = config || {} }, run: function(instance, callback) { var req = instance.req var re...
this.template = template || 'errors/default' this.templateOptions.layout = 'errors/layout' this.model = data return this._render(template, data) }
{ delete data.options delete data.stack delete data.error }
conditional_block
errors.js
var Plugin = require('nokomis/plugin') var Domain = require('domain') var ErrorPage = require('error-page') var _ = require('underscore') module.exports = Plugin.extend({ initialize: function(config) { this.config = config || {} }, run: function(instance, callback) { var req = instance.req var res...
} this.template = template || 'errors/default' this.templateOptions.layout = 'errors/layout' this.model = data return this._render(template, data) }
delete data.options delete data.stack delete data.error
random_line_split
errors.js
var Plugin = require('nokomis/plugin') var Domain = require('domain') var ErrorPage = require('error-page') var _ = require('underscore') module.exports = Plugin.extend({ initialize: function(config) { this.config = config || {} }, run: function(instance, callback) { var req = instance.req var re...
(req, res, data) { return handleError.call(this, req, res, data, 'errors/404') } /** * Handle 500 error * * @param {Object} req * @param {Object} res * @param {Object} data * @api private */ function handle500(req, res, data) { return handleError.call(this, req, res, data, 'errors/500') } /** * Handle al...
handle404
identifier_name
generator.py
from PIL import Image from PIL import ImageFont from PIL import ImageDraw from name_generator import get_random_name FONT_SIZE = 14 FONT = ImageFont.truetype("appletext.ttf", FONT_SIZE) def generate_new_tombstone(name, inscription): img = Image.open("created_tombstones/base_tombstone.png") draw = ImageDraw.Dr...
generate_new_tombstone("Aaron Montana", "Ate corndog with no mustard. Tried putting it in gravy. Died.")
return result if __name__ == '__main__':
random_line_split
generator.py
from PIL import Image from PIL import ImageFont from PIL import ImageDraw from name_generator import get_random_name FONT_SIZE = 14 FONT = ImageFont.truetype("appletext.ttf", FONT_SIZE) def generate_new_tombstone(name, inscription): img = Image.open("created_tombstones/base_tombstone.png") draw = ImageDraw.Dr...
if __name__ == '__main__': generate_new_tombstone("Aaron Montana", "Ate corndog with no mustard. Tried putting it in gravy. Died.")
n = 26 words = inscription.split() result = [] current = "" for word in words: current = "{} {}".format(current, word) if len(current) > n: result.append(current) current = "" if current: result.append(current) return result
identifier_body
generator.py
from PIL import Image from PIL import ImageFont from PIL import ImageDraw from name_generator import get_random_name FONT_SIZE = 14 FONT = ImageFont.truetype("appletext.ttf", FONT_SIZE) def generate_new_tombstone(name, inscription): img = Image.open("created_tombstones/base_tombstone.png") draw = ImageDraw.Dr...
(inscription): n = 26 words = inscription.split() result = [] current = "" for word in words: current = "{} {}".format(current, word) if len(current) > n: result.append(current) current = "" if current: result.append(current) return result if ...
split_inscription
identifier_name
generator.py
from PIL import Image from PIL import ImageFont from PIL import ImageDraw from name_generator import get_random_name FONT_SIZE = 14 FONT = ImageFont.truetype("appletext.ttf", FONT_SIZE) def generate_new_tombstone(name, inscription): img = Image.open("created_tombstones/base_tombstone.png") draw = ImageDraw.Dr...
return start_loc def split_inscription(inscription): n = 26 words = inscription.split() result = [] current = "" for word in words: current = "{} {}".format(current, word) if len(current) > n: result.append(current) current = "" if current: r...
start_loc = 330 + ((4-mid) * FONT_SIZE)
conditional_block
pages.py
# -*- coding: utf-8 -*- # Copyright(C) 2014 Bezleputh # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
def obj_details(self): details = dict() for item in XPath('//div[@class="features clearfix"]/ul/li')(self): key = CleanText('./span[@class="name"]')(item) value = CleanText('./span[@class="value"]')(item) if value and key: ...
for img in XPath('//a[@class="thumbnail-link"]/img[@itemprop="image"]')(self): url = Regexp(CleanText('./@src'), 'http://thbr\.figarocms\.net.*(http://.*)')(img) photos.append(HousingPhoto(url)) return photos
random_line_split
pages.py
# -*- coding: utf-8 -*- # Copyright(C) 2014 Bezleputh # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
): phone = CleanText('./div/div/ul/li/span[@class="js-clickphone"]', replace=[(u'Téléphoner : ', u'')], default=NotAvailable)(self) if '...' in phone: return NotLoaded return phone ...
hone(self
identifier_name
pages.py
# -*- coding: utf-8 -*- # Copyright(C) 2014 Bezleputh # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
key = CleanText('//div[@class="title-dpe clearfix"]')(self) value = CleanText('//div[@class="energy-consumption"]')(self) if value and key: details[key] = value return details
t('./span[@class="name"]')(item) value = CleanText('./span[@class="value"]')(item) if value and key: details[key] = value
conditional_block
pages.py
# -*- coding: utf-8 -*- # Copyright(C) 2014 Bezleputh # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
return phone def obj_photos(self): url = CleanText('./div/div/a/img[@itemprop="image"]/@src')(self) return [HousingPhoto(url)] clas s TypeDecimal(Filter): def filter(self, el): return Decimal(el) class FromTimestamp(Filter): def filter(sel...
klass = Housing obj_id = CleanText('./@data-classified-id') obj_title = CleanText('./div/h2[@itemprop="name"]/a') obj_location = CleanText('./div/h2[@itemprop="name"]/span[class="item-localisation"]') obj_cost = CleanDecimal('./div/div/span[@class="price-label"]') ...
identifier_body
lxde.py
# # xfce.py # # Copyright (C) 2010 Fabio Erculiani # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is...
def setSteps(self, anaconda): BaseInstallClass.setSteps(self, anaconda) anaconda.dispatch.skipStep("welcome", skip = 1) #anaconda.dispatch.skipStep("network", skip = 1) def getBackend(self): return LiveCDCopyBackend def productMatches(self, oldprod): if oldprod is...
BaseInstallClass.configure(self, anaconda) BaseInstallClass.setDefaultPartitioning(self, anaconda.storage, anaconda.platform)
identifier_body
lxde.py
# # xfce.py # # Copyright (C) 2010 Fabio Erculiani # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is...
def getBackend(self): return LiveCDCopyBackend def productMatches(self, oldprod): if oldprod is None: return False if oldprod.startswith(productName): return True return False def versionMatches(self, oldver): try: oldVer = floa...
random_line_split
lxde.py
# # xfce.py # # Copyright (C) 2010 Fabio Erculiani # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is...
(self): return LiveCDCopyBackend def productMatches(self, oldprod): if oldprod is None: return False if oldprod.startswith(productName): return True return False def versionMatches(self, oldver): try: oldVer = float(oldver) ...
getBackend
identifier_name
lxde.py
# # xfce.py # # Copyright (C) 2010 Fabio Erculiani # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is...
return False def versionMatches(self, oldver): try: oldVer = float(oldver) newVer = float(productVersion) except ValueError: return True return newVer >= oldVer def __init__(self): BaseInstallClass.__init__(self)
return True
conditional_block
websocket.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {patchEventTarget} from '../common/events'; import {ADD_EVENT_LISTENER_STR, ArraySlice, ObjectCreate, ObjectG...
(api: _ZonePrivate, _global: any) { const WS = (<any>_global).WebSocket; // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener // On older Chrome, no need since EventTarget was already patched if (!(<any>_global).EventTarget) { patchEventTarget(_global, [WS.prototype]); ...
apply
identifier_name
websocket.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {patchEventTarget} from '../common/events'; import {ADD_EVENT_LISTENER_STR, ArraySlice, ObjectCreate, ObjectG...
proxySocketProto = socket; [ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(function( propName) { proxySocket[propName] = function() { const args = ArraySlice.call(arguments); if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVE...
{ const WS = (<any>_global).WebSocket; // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener // On older Chrome, no need since EventTarget was already patched if (!(<any>_global).EventTarget) { patchEventTarget(_global, [WS.prototype]); } (<any>_global).WebSocket = fu...
identifier_body
websocket.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {patchEventTarget} from '../common/events'; import {ADD_EVENT_LISTENER_STR, ArraySlice, ObjectCreate, ObjectG...
}
random_line_split
websocket.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {patchEventTarget} from '../common/events'; import {ADD_EVENT_LISTENER_STR, ArraySlice, ObjectCreate, ObjectG...
} else { // we can patch the real socket proxySocket = socket; } patchOnProperties(proxySocket, ['close', 'error', 'message', 'open'], proxySocketProto); return proxySocket; }; const globalWebSocket = _global['WebSocket']; for (const prop in WS) { globalWebSocket[prop] = WS[prop...
{ proxySocket = ObjectCreate(socket); // socket have own property descriptor 'onopen', 'onmessage', 'onclose', 'onerror' // but proxySocket not, so we will keep socket as prototype and pass it to // patchOnProperties method proxySocketProto = socket; [ADD_EVENT_LISTENER_STR, REMOVE_E...
conditional_block
get_locals.py
#!/usr/bin/env python import rospy import actionlib from actionlib_msgs.msg import * from geometry_msgs.msg import PoseStampted import yaml import os import os.path class GetLocals: def __init__(self): rospy.Subscriber('move_base_simple/goal', PoseStampted, self.goal_callback) print('\nPLEASE, SEND A GOAL WITH...
(self, data): self.fname = os.path.expanduser('~') + '/catkin_ws/src/approach_control/approach_control_config/config/locals.yaml' stream = open(self.fname, 'r') self.data = yaml.load(stream) self.keys = self.data.keys() local = raw_input('Please, write the location for this point (if doesnt exist it will be ...
goal_callback
identifier_name
get_locals.py
#!/usr/bin/env python import rospy import actionlib from actionlib_msgs.msg import * from geometry_msgs.msg import PoseStampted import yaml import os import os.path class GetLocals:
c = raw_input('Save as a new place? (Y/N)') if c.lower() == 'y': self.data[local] = [[data.pose.position.x, data.pose.position.y], [0.0, 0.0, data.pose.orientation.z, data.pose.orientation.w]] with open(self.fname, 'w') as yaml_file: yaml_file.write(yaml.dump(self.data, default_flow_style = False)) ...
def __init__(self): rospy.Subscriber('move_base_simple/goal', PoseStampted, self.goal_callback) print('\nPLEASE, SEND A GOAL WITH NAV 2D GOAL USING GRAPHIC USER INTERFACE TO SAVE A POINT!\n') def goal_callback(self, data): self.fname = os.path.expanduser('~') + '/catkin_ws/src/approach_control/approach_contro...
identifier_body
get_locals.py
#!/usr/bin/env python import rospy
from geometry_msgs.msg import PoseStampted import yaml import os import os.path class GetLocals: def __init__(self): rospy.Subscriber('move_base_simple/goal', PoseStampted, self.goal_callback) print('\nPLEASE, SEND A GOAL WITH NAV 2D GOAL USING GRAPHIC USER INTERFACE TO SAVE A POINT!\n') def goal_callback(sel...
import actionlib from actionlib_msgs.msg import *
random_line_split
get_locals.py
#!/usr/bin/env python import rospy import actionlib from actionlib_msgs.msg import * from geometry_msgs.msg import PoseStampted import yaml import os import os.path class GetLocals: def __init__(self): rospy.Subscriber('move_base_simple/goal', PoseStampted, self.goal_callback) print('\nPLEASE, SEND A GOAL WITH...
if __name__ == '__main__': GetLocals() rospy.init_node('getlocals', anonymous = True) try: rospy.spin() except KeyboardInterrupt: rospy.loginfo('Shutting down!')
c = raw_input('Save as a new place? (Y/N)') if c.lower() == 'y': self.data[local] = [[data.pose.position.x, data.pose.position.y], [0.0, 0.0, data.pose.orientation.z, data.pose.orientation.w]] with open(self.fname, 'w') as yaml_file: yaml_file.write(yaml.dump(self.data, default_flow_style = False)) ...
conditional_block
jquery.highlight.js
_callable is_dir is_double '+ 'is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long '+ 'is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault '+ 'is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br '+ ...
'second section select sequence serializable set size smallint static ' + 'statistics table temp temporary then time timestamp to top transaction ' +
random_line_split
jquery.highlight.js
span class="com">//$1</span>') //replace variables .replace(/\$(\w+)/g,'<span class="var">$$$1</span>') //replace functions .replace(funcs,'<span class="fnc">$1</span>$2') //replace keywords .replace(keywords,'<span class="kwd">$1</span>$2'); return code; }, //CSS hightlight_css: fun...
push
identifier_name
jquery.highlight.js
(/\$(\w+)/g,'<span class="var">$$$1</span>') //replace functions .replace(funcs,'<span class="fnc">$1</span>$2') //replace keywords .replace(keywords,'<span class="kwd">$1</span>$2'); return code; }, //CSS hightlight_css: function(code) { var comments = []; // store comments v...
{ array.push(element); return array.length-1; }
identifier_body
foreman.py
# Details about hosts in the inventory self.params = dict() # Params of each host self.facts = dict() # Facts of each host self.hostgroups = dict() # host groups self.hostcollections = dict() # host collections self.session = None # Requests session self.config_pa...
self, host): """Fetch all host facts of the host""" if not self.want_facts: return {} ret = self._get_facts_by_id(host['id']) if len(ret.values()) == 0: facts = {} elif len(ret.values()) == 1: facts = list(ret.values())[0] else: ...
get_facts(
identifier_name
foreman.py
# Details about hosts in the inventory self.params = dict() # Params of each host self.facts = dict() # Facts of each host self.hostgroups = dict() # host groups self.hostcollections = dict() # host collections self.session = None # Requests session self.config_pa...
to_text(val).lower() )) self.inventory[safe_key].append(dns_name) # Create ansible groups for environment, location and organization for group in ['environment', 'location', 'organization']: val = host.get('%s_name' % group) ...
""Make calls to foreman and save the output in a cache""" self.groups = dict() self.hosts = dict() for host in self._get_hosts(): if host['name'] in self.cache.keys() and scan_only_new_hosts: continue dns_name = host['name'] host_data = self...
identifier_body
foreman.py
# Details about hosts in the inventory self.params = dict() # Params of each host self.facts = dict() # Facts of each host self.hostgroups = dict() # host groups self.hostcollections = dict() # host collections self.session = None # Requests session self.config_pa...
return facts def write_to_cache(self, data, filename): """Write data in JSON format to a file""" json_data = json_format_dict(data, True) cache = open(filename, 'w') cache.write(json_data) cache.close() def _write_cache(self): self.write_to_cache(self.ca...
aise ValueError("More than one set of facts returned for '%s'" % host)
conditional_block
foreman.py
# 3rd party imports import requests if LooseVersion(requests.__version__) < LooseVersion('1.1.0'): print('This script requires python-requests 1.1 as a minimum version') sys.exit(1) from requests.auth import HTTPBasicAuth from ansible.module_utils._text import to_text def json_format_dict(data, pretty=False...
from collections import defaultdict from distutils.version import LooseVersion, StrictVersion
random_line_split