file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
plugin.py
# -*- coding: utf-8 -*- """ Base Class for InvenTree plugins """ import warnings from django.db.utils import OperationalError, ProgrammingError from django.utils.text import slugify class InvenTreePluginBase(): """ Base class for a plugin DO NOT USE THIS DIRECTLY, USE plugin.IntegrationPluginBase """ def __init__(self): pass # Override the plugin name for each concrete plugin instance PLUGIN_NAME = '' PLUGIN_SLUG = None PLUGIN_TITLE = None def plugin_name(self): """ Name of plugin """ return self.PLUGIN_NAME def plugin_slug(self): """ Slug of plugin If not set plugin name slugified """ slug = getattr(self, 'PLUGIN_SLUG', None) if slug is None: slug = self.plugin_name() return slugify(slug.lower()) def plugin_title(self): """ Title of plugin """ if self.PLUGIN_TITLE: return self.PLUGIN_TITLE else: return self.plugin_name() def plugin_config(self, raise_error=False): """ Return the PluginConfig object associated with this plugin """ try: import plugin.models cfg, _ = plugin.models.PluginConfig.objects.get_or_create( key=self.plugin_slug(), name=self.plugin_name(), ) except (OperationalError, ProgrammingError) as error: cfg = None if raise_error: raise error return cfg def is_active(self): """ Return True if this plugin is currently active """ cfg = self.plugin_config() if cfg: return cfg.active else: return False # TODO @matmair remove after InvenTree 0.7.0 release class InvenTreePlugin(InvenTreePluginBase):
""" This is here for leagcy reasons and will be removed in the next major release """ def __init__(self): warnings.warn("Using the InvenTreePlugin is depreceated", DeprecationWarning) super().__init__()
identifier_body
index.ts
import { Application, Model, Property, QueryHandler, ActionHandler, Validator, SchemaTypeDefinition, IRequestContext, VALIDATORS } from 'vulcain-corejs'; // Define and register a new custom type (or validator) @SchemaTypeDefinition() class Age { type = "number"; // Define a sub type (optional) // Custom property $min: number = 0;
(val: number, context?: IRequestContext) { if (val < this.$min || val > 123) return "Age must be between {$min} and 123"; return null; } // Optional coerce method // used to convert the input value // coerce(val): number { return val;} } @Model() export class Hobby { @Property({ type: "string", required: true }) name: string; } @Model({ validate: Customer.validate}) @ActionHandler({ scope: '?' }) // Anonymous access @QueryHandler({scope: '?'}) // Anonymous access class Customer { // Entity validation static validate(entity: Customer, context: IRequestContext): string { if (entity.firstName === entity.lastName) return "Invalid customer name"; return; } // Public (exposed) property must have a Property annotation to be validated and bounded @Property({ type: 'string', required: true, description: "First name" }) @Validator(VALIDATORS.Length, { min: 4 }) firstName: string; @Property({ type: 'string', required: true, description: "Last name" }) @Validator("pattern", { pattern: /^[A-Z]\w*/ }) lastName: string; // Custom type @Property({ type: "Age", required: true, typeProperties: { min: 10 } }) age: number; @Property({ type: "uid", isKey: true }) // Create a new unique id if empty id: string; @Property({ type: "Hobby", cardinality: "many" }) hobbies: Hobby[]; } // Start service let srv = new Application('Sample').enableGraphQL(); srv.start(8080);
validate
identifier_name
index.ts
import { Application, Model, Property, QueryHandler, ActionHandler, Validator, SchemaTypeDefinition, IRequestContext, VALIDATORS } from 'vulcain-corejs'; // Define and register a new custom type (or validator) @SchemaTypeDefinition() class Age { type = "number"; // Define a sub type (optional) // Custom property $min: number = 0; validate(val: number, context?: IRequestContext) { if (val < this.$min || val > 123) return "Age must be between {$min} and 123"; return null; } // Optional coerce method // used to convert the input value // coerce(val): number { return val;} } @Model() export class Hobby { @Property({ type: "string", required: true }) name: string; } @Model({ validate: Customer.validate}) @ActionHandler({ scope: '?' }) // Anonymous access @QueryHandler({scope: '?'}) // Anonymous access class Customer { // Entity validation static validate(entity: Customer, context: IRequestContext): string { if (entity.firstName === entity.lastName) return "Invalid customer name"; return; } // Public (exposed) property must have a Property annotation to be validated and bounded @Property({ type: 'string', required: true, description: "First name" }) @Validator(VALIDATORS.Length, { min: 4 }) firstName: string; @Property({ type: 'string', required: true, description: "Last name" }) @Validator("pattern", { pattern: /^[A-Z]\w*/ })
lastName: string; // Custom type @Property({ type: "Age", required: true, typeProperties: { min: 10 } }) age: number; @Property({ type: "uid", isKey: true }) // Create a new unique id if empty id: string; @Property({ type: "Hobby", cardinality: "many" }) hobbies: Hobby[]; } // Start service let srv = new Application('Sample').enableGraphQL(); srv.start(8080);
random_line_split
progress_bar.py
from lib.font import * import sys import fcntl import termios import struct class progress_bar(object): def __init__(self, tot=100, lenght=10): self.cp='/-\|' self.bar_lenght = lenght self.tot = tot def startprogress(self, title): """Creates a progress bar 40 chars long on the console and moves cursor back to beginning with BS character""" sys.stdout.write(title + ": [" + "-" * self.bar_lenght + "]" + chr(8) * (self.bar_lenght+1)) sys.stdout.flush() def progress(self, x): """Sets progress bar to a certain percentage x. Progress is given as whole percentage, i.e. 50% done is given by x = 50""" y = int(x)%4 z = int((x/float(self.tot))*self.bar_lenght) sys.stdout.write("#" * z + self.cp[y] +"-" * (self.bar_lenght-1 - z) + "] "+ bold(str(int(x))+"/"+str(self.tot)) + chr(8) * (self.bar_lenght+4+len(str(int(x)))+len(str(self.tot)) )) sys.stdout.flush() def endprogress(self): """End of progress bar; Write full bar, then move to next line""" sys.stdout.write("#" * self.bar_lenght + "]\n") sys.stdout.flush() class all_line_progress_bar(object): def __init__(self): self.COLS = struct.unpack('hh', fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234'))[1] def progress(self,current, total): prefix = '%d / %d' % (current, total) bar_start = ' [' bar_end = '] ' bar_size = self.COLS - len(prefix + bar_start + bar_end) amount = int(current / (total / float(bar_size))) remain = bar_size - amount bar = '#' * amount + ' ' * remain return bold(prefix) + bar_start + bar + bar_end def bar(self, current, total):
sys.stdout.write(self.progress(current,total) + '\r') sys.stdout.flush()
identifier_body
progress_bar.py
from lib.font import * import sys import fcntl import termios import struct class progress_bar(object):
self.tot = tot def startprogress(self, title): """Creates a progress bar 40 chars long on the console and moves cursor back to beginning with BS character""" sys.stdout.write(title + ": [" + "-" * self.bar_lenght + "]" + chr(8) * (self.bar_lenght+1)) sys.stdout.flush() def progress(self, x): """Sets progress bar to a certain percentage x. Progress is given as whole percentage, i.e. 50% done is given by x = 50""" y = int(x)%4 z = int((x/float(self.tot))*self.bar_lenght) sys.stdout.write("#" * z + self.cp[y] +"-" * (self.bar_lenght-1 - z) + "] "+ bold(str(int(x))+"/"+str(self.tot)) + chr(8) * (self.bar_lenght+4+len(str(int(x)))+len(str(self.tot)) )) sys.stdout.flush() def endprogress(self): """End of progress bar; Write full bar, then move to next line""" sys.stdout.write("#" * self.bar_lenght + "]\n") sys.stdout.flush() class all_line_progress_bar(object): def __init__(self): self.COLS = struct.unpack('hh', fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234'))[1] def progress(self,current, total): prefix = '%d / %d' % (current, total) bar_start = ' [' bar_end = '] ' bar_size = self.COLS - len(prefix + bar_start + bar_end) amount = int(current / (total / float(bar_size))) remain = bar_size - amount bar = '#' * amount + ' ' * remain return bold(prefix) + bar_start + bar + bar_end def bar(self, current, total): sys.stdout.write(self.progress(current,total) + '\r') sys.stdout.flush()
def __init__(self, tot=100, lenght=10): self.cp='/-\|' self.bar_lenght = lenght
random_line_split
progress_bar.py
from lib.font import * import sys import fcntl import termios import struct class progress_bar(object): def __init__(self, tot=100, lenght=10): self.cp='/-\|' self.bar_lenght = lenght self.tot = tot def
(self, title): """Creates a progress bar 40 chars long on the console and moves cursor back to beginning with BS character""" sys.stdout.write(title + ": [" + "-" * self.bar_lenght + "]" + chr(8) * (self.bar_lenght+1)) sys.stdout.flush() def progress(self, x): """Sets progress bar to a certain percentage x. Progress is given as whole percentage, i.e. 50% done is given by x = 50""" y = int(x)%4 z = int((x/float(self.tot))*self.bar_lenght) sys.stdout.write("#" * z + self.cp[y] +"-" * (self.bar_lenght-1 - z) + "] "+ bold(str(int(x))+"/"+str(self.tot)) + chr(8) * (self.bar_lenght+4+len(str(int(x)))+len(str(self.tot)) )) sys.stdout.flush() def endprogress(self): """End of progress bar; Write full bar, then move to next line""" sys.stdout.write("#" * self.bar_lenght + "]\n") sys.stdout.flush() class all_line_progress_bar(object): def __init__(self): self.COLS = struct.unpack('hh', fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234'))[1] def progress(self,current, total): prefix = '%d / %d' % (current, total) bar_start = ' [' bar_end = '] ' bar_size = self.COLS - len(prefix + bar_start + bar_end) amount = int(current / (total / float(bar_size))) remain = bar_size - amount bar = '#' * amount + ' ' * remain return bold(prefix) + bar_start + bar + bar_end def bar(self, current, total): sys.stdout.write(self.progress(current,total) + '\r') sys.stdout.flush()
startprogress
identifier_name
util.py
# -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, division) import json import re import six import sys channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;]+\Z') app_id_re = re.compile('\A[0-9]+\Z') pusher_url_re = re.compile('\A(http|https)://(.*):(.*)@(.*)/apps/([0-9]+)\Z') socket_id_re = re.compile('\A\d+\.\d+\Z') if sys.version_info < (3,): text = 'a unicode string'
else: text = 'a string' def ensure_text(obj, name): if isinstance(obj, six.text_type): return obj if isinstance(obj, six.string_types): return six.text_type(obj) raise TypeError("%s should be %s" % (name, text)) def validate_channel(channel): channel = ensure_text(channel, "channel") if len(channel) > 200: raise ValueError("Channel too long: %s" % channel) if not channel_name_re.match(channel): raise ValueError("Invalid Channel: %s" % channel) return channel def validate_socket_id(socket_id): socket_id = ensure_text(socket_id, "socket_id") if not socket_id_re.match(socket_id): raise ValueError("Invalid socket ID: %s" % socket_id) return socket_id
random_line_split
util.py
# -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, division) import json import re import six import sys channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;]+\Z') app_id_re = re.compile('\A[0-9]+\Z') pusher_url_re = re.compile('\A(http|https)://(.*):(.*)@(.*)/apps/([0-9]+)\Z') socket_id_re = re.compile('\A\d+\.\d+\Z') if sys.version_info < (3,): text = 'a unicode string' else: text = 'a string' def ensure_text(obj, name): if isinstance(obj, six.text_type): return obj if isinstance(obj, six.string_types): return six.text_type(obj) raise TypeError("%s should be %s" % (name, text)) def validate_channel(channel):
def validate_socket_id(socket_id): socket_id = ensure_text(socket_id, "socket_id") if not socket_id_re.match(socket_id): raise ValueError("Invalid socket ID: %s" % socket_id) return socket_id
channel = ensure_text(channel, "channel") if len(channel) > 200: raise ValueError("Channel too long: %s" % channel) if not channel_name_re.match(channel): raise ValueError("Invalid Channel: %s" % channel) return channel
identifier_body
util.py
# -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, division) import json import re import six import sys channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;]+\Z') app_id_re = re.compile('\A[0-9]+\Z') pusher_url_re = re.compile('\A(http|https)://(.*):(.*)@(.*)/apps/([0-9]+)\Z') socket_id_re = re.compile('\A\d+\.\d+\Z') if sys.version_info < (3,): text = 'a unicode string' else: text = 'a string' def ensure_text(obj, name): if isinstance(obj, six.text_type): return obj if isinstance(obj, six.string_types):
raise TypeError("%s should be %s" % (name, text)) def validate_channel(channel): channel = ensure_text(channel, "channel") if len(channel) > 200: raise ValueError("Channel too long: %s" % channel) if not channel_name_re.match(channel): raise ValueError("Invalid Channel: %s" % channel) return channel def validate_socket_id(socket_id): socket_id = ensure_text(socket_id, "socket_id") if not socket_id_re.match(socket_id): raise ValueError("Invalid socket ID: %s" % socket_id) return socket_id
return six.text_type(obj)
conditional_block
util.py
# -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, division) import json import re import six import sys channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;]+\Z') app_id_re = re.compile('\A[0-9]+\Z') pusher_url_re = re.compile('\A(http|https)://(.*):(.*)@(.*)/apps/([0-9]+)\Z') socket_id_re = re.compile('\A\d+\.\d+\Z') if sys.version_info < (3,): text = 'a unicode string' else: text = 'a string' def ensure_text(obj, name): if isinstance(obj, six.text_type): return obj if isinstance(obj, six.string_types): return six.text_type(obj) raise TypeError("%s should be %s" % (name, text)) def validate_channel(channel): channel = ensure_text(channel, "channel") if len(channel) > 200: raise ValueError("Channel too long: %s" % channel) if not channel_name_re.match(channel): raise ValueError("Invalid Channel: %s" % channel) return channel def
(socket_id): socket_id = ensure_text(socket_id, "socket_id") if not socket_id_re.match(socket_id): raise ValueError("Invalid socket ID: %s" % socket_id) return socket_id
validate_socket_id
identifier_name
graph-node.ts
import { Graph } from './graph'; import { Link } from './graph-links'; /** * Represents a node in a {@link Graph}. * * @hidden * @category Graph */ export abstract class GraphNode { private _disposed = false; constructor(protected readonly graph: Graph<GraphNode>) { this.graph = graph; } /** * Returns true if links between this and the given node are allowed. Validates only that the * objects are both {@link GraphNode} instances and on the same graph, not that they are * semantically compatible. * * @internal */ public canLink(other: GraphNode): boolean { return this.graph === other.graph; } /** Returns true if the node has been permanently removed from the graph. */ public isDisposed(): boolean { return this._disposed; } /** * Removes both inbound references to and outbound references from this object. At the end * of the process the object holds no references, and nothing holds references to it. A * disposed object is not reusable. */ public dispose(): void { this.graph.disconnectChildren(this); this.graph.disconnectParents(this); this._disposed = true; this.graph.emit('dispose', this); } /** * Removes all inbound references to this object. At the end of the process the object is * considered 'detached': it may hold references to child resources, but nothing holds * references to it. A detached object may be re-attached. */ public detach(): this { this.graph.disconnectParents(this); return this; } /** * Transfers this object's references from the old node to the new one. The old node is fully * detached from this parent at the end of the process. * * @hidden This method works imperfectly with Root, Scene, and Node properties, which may * already hold equivalent links to the replacement object. */ public swap(old: GraphNode, replacement: GraphNode): this
/** * Adds a Link to a managed {@link @GraphChildList}, and sets up a listener to * remove the link if it's disposed. This function is only for lists of links, * annotated with {@link @GraphChildList}. Properties are annotated and managed by * {@link @GraphChild} instead. * * @hidden */ protected addGraphChild(links: Link<GraphNode, GraphNode>[], link: Link<GraphNode, GraphNode>): this { links.push(link); link.onDispose(() => { const remaining = links.filter((l) => l !== link); links.length = 0; for (const link of remaining) links.push(link); }); return this; } /** * Removes a {@link GraphNode} from a {@link GraphChildList}. * * @hidden */ protected removeGraphChild(links: Link<GraphNode, GraphNode>[], child: GraphNode): this { const pruned = links.filter((link) => link.getChild() === child); pruned.forEach((link) => link.dispose()); return this; } /** * Removes all {@link GraphNode}s from a {@link GraphChildList}. * * @hidden */ protected clearGraphChildList(links: Link<GraphNode, GraphNode>[]): this { while (links.length > 0) links[0].dispose(); return this; } /** * Returns a list of all nodes that hold a reference to this node. * * Available publicly by {@link Property}'s `.listParents()`. * * @hidden */ protected listGraphParents(): GraphNode[] { return this.graph.listParents(this) as GraphNode[]; } }
{ this.graph.swapChild(this, old, replacement); return this; }
identifier_body
graph-node.ts
import { Graph } from './graph'; import { Link } from './graph-links'; /** * Represents a node in a {@link Graph}. * * @hidden * @category Graph */ export abstract class GraphNode { private _disposed = false; constructor(protected readonly graph: Graph<GraphNode>) { this.graph = graph; } /** * Returns true if links between this and the given node are allowed. Validates only that the * objects are both {@link GraphNode} instances and on the same graph, not that they are * semantically compatible. * * @internal */ public canLink(other: GraphNode): boolean { return this.graph === other.graph; } /** Returns true if the node has been permanently removed from the graph. */ public
(): boolean { return this._disposed; } /** * Removes both inbound references to and outbound references from this object. At the end * of the process the object holds no references, and nothing holds references to it. A * disposed object is not reusable. */ public dispose(): void { this.graph.disconnectChildren(this); this.graph.disconnectParents(this); this._disposed = true; this.graph.emit('dispose', this); } /** * Removes all inbound references to this object. At the end of the process the object is * considered 'detached': it may hold references to child resources, but nothing holds * references to it. A detached object may be re-attached. */ public detach(): this { this.graph.disconnectParents(this); return this; } /** * Transfers this object's references from the old node to the new one. The old node is fully * detached from this parent at the end of the process. * * @hidden This method works imperfectly with Root, Scene, and Node properties, which may * already hold equivalent links to the replacement object. */ public swap(old: GraphNode, replacement: GraphNode): this { this.graph.swapChild(this, old, replacement); return this; } /** * Adds a Link to a managed {@link @GraphChildList}, and sets up a listener to * remove the link if it's disposed. This function is only for lists of links, * annotated with {@link @GraphChildList}. Properties are annotated and managed by * {@link @GraphChild} instead. * * @hidden */ protected addGraphChild(links: Link<GraphNode, GraphNode>[], link: Link<GraphNode, GraphNode>): this { links.push(link); link.onDispose(() => { const remaining = links.filter((l) => l !== link); links.length = 0; for (const link of remaining) links.push(link); }); return this; } /** * Removes a {@link GraphNode} from a {@link GraphChildList}. * * @hidden */ protected removeGraphChild(links: Link<GraphNode, GraphNode>[], child: GraphNode): this { const pruned = links.filter((link) => link.getChild() === child); pruned.forEach((link) => link.dispose()); return this; } /** * Removes all {@link GraphNode}s from a {@link GraphChildList}. * * @hidden */ protected clearGraphChildList(links: Link<GraphNode, GraphNode>[]): this { while (links.length > 0) links[0].dispose(); return this; } /** * Returns a list of all nodes that hold a reference to this node. * * Available publicly by {@link Property}'s `.listParents()`. * * @hidden */ protected listGraphParents(): GraphNode[] { return this.graph.listParents(this) as GraphNode[]; } }
isDisposed
identifier_name
graph-node.ts
import { Graph } from './graph'; import { Link } from './graph-links'; /** * Represents a node in a {@link Graph}. * * @hidden * @category Graph */ export abstract class GraphNode { private _disposed = false; constructor(protected readonly graph: Graph<GraphNode>) { this.graph = graph; } /** * Returns true if links between this and the given node are allowed. Validates only that the * objects are both {@link GraphNode} instances and on the same graph, not that they are * semantically compatible. * * @internal */ public canLink(other: GraphNode): boolean { return this.graph === other.graph; } /** Returns true if the node has been permanently removed from the graph. */ public isDisposed(): boolean { return this._disposed; } /** * Removes both inbound references to and outbound references from this object. At the end * of the process the object holds no references, and nothing holds references to it. A * disposed object is not reusable. */ public dispose(): void { this.graph.disconnectChildren(this); this.graph.disconnectParents(this); this._disposed = true; this.graph.emit('dispose', this); } /** * Removes all inbound references to this object. At the end of the process the object is * considered 'detached': it may hold references to child resources, but nothing holds * references to it. A detached object may be re-attached. */ public detach(): this { this.graph.disconnectParents(this); return this; } /** * Transfers this object's references from the old node to the new one. The old node is fully * detached from this parent at the end of the process. * * @hidden This method works imperfectly with Root, Scene, and Node properties, which may * already hold equivalent links to the replacement object. */ public swap(old: GraphNode, replacement: GraphNode): this { this.graph.swapChild(this, old, replacement); return this; } /** * Adds a Link to a managed {@link @GraphChildList}, and sets up a listener to * remove the link if it's disposed. This function is only for lists of links, * annotated with {@link @GraphChildList}. Properties are annotated and managed by
* {@link @GraphChild} instead. * * @hidden */ protected addGraphChild(links: Link<GraphNode, GraphNode>[], link: Link<GraphNode, GraphNode>): this { links.push(link); link.onDispose(() => { const remaining = links.filter((l) => l !== link); links.length = 0; for (const link of remaining) links.push(link); }); return this; } /** * Removes a {@link GraphNode} from a {@link GraphChildList}. * * @hidden */ protected removeGraphChild(links: Link<GraphNode, GraphNode>[], child: GraphNode): this { const pruned = links.filter((link) => link.getChild() === child); pruned.forEach((link) => link.dispose()); return this; } /** * Removes all {@link GraphNode}s from a {@link GraphChildList}. * * @hidden */ protected clearGraphChildList(links: Link<GraphNode, GraphNode>[]): this { while (links.length > 0) links[0].dispose(); return this; } /** * Returns a list of all nodes that hold a reference to this node. * * Available publicly by {@link Property}'s `.listParents()`. * * @hidden */ protected listGraphParents(): GraphNode[] { return this.graph.listParents(this) as GraphNode[]; } }
random_line_split
index.d.ts
// Type definitions for linkedin dustjs 1.2.1 // Project: https://github.com/linkedin/dustjs // Definitions by: Marcelo Dezem <https://github.com/mdezem> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // // Due to a lack of documentation it's not possible // to know which methods are intended to be public and which // are intended to be used internally by the framework. // All the interfaces definitions here exposes only the methods // that are documented in some way (tutorials, guides, references, etc.). // // Fell free to include other methods. If possible let me know about. // /** * A template compiled into a js function. */ export interface Template { (chk: Chunk, ctx: Context): Chunk; } export interface Chunk { /** * Writes data to this chunk's buffer. */ write(data: string): Chunk; /** * Writes data to this chunk's buffer and marks it as flushable. This method must be called on any chunks created via chunk.map. Do not call this method on a handler's main chunk -- dust.render and dust.stream take care of this for you. */ end(data: string): Chunk; /** * Creates a new chunk and passes it to callback. Use map to wrap asynchronous functions and to partition the template for streaming. */ map(callback: (chunk: Chunk) => any): Chunk; /** * Convenience method to apply filters to a stream. */ tap(callback: (value: any) => any): Chunk; /** * Removes the head tap function from the list. */ untap(): Chunk; /** * Renders a template block, such as a default block or an else block. */ render(body: any, context: Context): Chunk; /** * Sets an error on this chunk and immediately flushes the output. */ setError(err: any): Chunk; } export interface Context { /** * Retrieves the value at key from the context stack. */ get(key: string): any; /** * Pushes an arbitrary value onto the context stack and returns a new context instance. Specify index and/or length to enable enumeration helpers. */ push(head: any, idx?: number, len?: number): Context; /** * Returns a new context instance consisting only of the value at head, plus any previously defined global object. */ rebase(head: any): Context; /** * Returns the head of the context stack. */ current(): any; } export interface Stream { flush(): void; emit(evt: string, data: any): void; /* * Registers an event listener. Streams accept a single listener for a given event. * @param evt the event. Possible values are data, end, error (maybe more, look in the source). */ on(evt: string, callback: (data?: any) => any): this; pipe(stream: Stream): Stream; } /** * register a template into the cache. * @param name the unique template name. * @param tmpl the template function. */ export declare function register(name: string, tmpl: Template): void; /** * compile a template body into a string of JavaScript source code * @param source the template string * @param name the name used to register the compiled template into the internal cache. See render(). * @strip strip whitespaces from the output. Defaults to false. */ export declare function compile(source: string, name: string, strip?: boolean): string; /** * Compiles source directly into a JavaScript function that takes a context and an optional callback (see dust.renderSource). Registers the template under [name] if this argument is supplied. * @param source the template string * @param name the template name (optional). */ export declare function compileFn(source: string, name?: string): Template; /** * Evaluates a compiled source string. */ export declare function loadSource(compiled: string): Template; /** * Renders the named template and calls callback on completion.context may be a plain object or an instance of dust.Context. * @param name the template name.
/** * Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required. * @param source the template string. * @param context a plain object or an instance of dust.Context. * @param callback (optional). If supplied the callback will be called passing the result string. If omitted, renderSource() will return a dust.Stream object. */ export declare function renderSource(source: string, context: any): Stream; export declare function renderSource(source: string, context: Context): Stream; export declare function renderSource(source: string, context: any, callback: (err: any, out: string) => any): void; export declare function renderSource(source: string, context: Context, callback: (err: any, out: string) => any): void; /** * Streams the named template. context may be a plain object or an instance of dust.Context. Returns an instance of dust.Stream. * @param name the template name. * @param context a plain object or an instance of dust.Context. */ export declare function stream(name: string, context: any): Stream; export declare function stream(name: string, context: Context): Stream; /** * Manufactures a dust.Context instance with its global object set to object. * @param global a plain object or an instance of dust.Context. */ export declare function makeBase(global: any): Context; export declare function makeBase(global: Context): Context; export declare function escapeHtml(html: string): string; export declare function escapeJs(js: string): string; declare var helpers: { [key: string]: (chk: Chunk, ctx: Context, bodies?: any, params?: any) => any; }; declare var filters: { [key: string]: (value: string) => string; };
* @param context a plain object or an instance of dust.Context. */ export declare function render(name: string, context: any, callback: (err: any, out: string) => any): void; export declare function render(name: string, context: Context, callback: (err: any, out: string) => any): void;
random_line_split
test-array_fill.js
// warning: This file is auto generated by `npm run build:tests` // Do not edit by hand! process.env.TZ = 'UTC' var expect = require('chai').expect var ini_set = require('../../../../src/php/info/ini_set') // eslint-disable-line no-unused-vars,camelcase var ini_get = require('../../../../src/php/info/ini_get') // eslint-disable-line no-unused-vars,camelcase var array_fill = require('../../../../src/php/array/array_fill.js') // eslint-disable-line no-unused-vars,camelcase
describe('src/php/array/array_fill.js (tested in test/languages/php/array/test-array_fill.js)', function () { it('should pass example 1', function (done) { var expected = { 5: 'banana', 6: 'banana', 7: 'banana', 8: 'banana', 9: 'banana', 10: 'banana' } var result = array_fill(5, 6, 'banana') expect(result).to.deep.equal(expected) done() }) })
random_line_split
clipboard_provider.rs
use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; use collections::borrow::ToOwned; use std::sync::mpsc::channel; pub trait ClipboardProvider { // blocking method to get the clipboard contents fn get_clipboard_contents(&mut self) -> String; // blocking method to set the clipboard contents fn set_clipboard_contents(&mut self, &str); } impl ClipboardProvider for ConstellationChan { fn get_clipboard_contents(&mut self) -> String { let (tx, rx) = channel(); self.0.send(ConstellationMsg::GetClipboardContents(tx)).unwrap(); rx.recv().unwrap() } fn set_clipboard_contents(&mut self, _: &str) { panic!("not yet implemented"); } } pub struct DummyClipboardContext { content: String } impl DummyClipboardContext { pub fn new(s: &str) -> DummyClipboardContext { DummyClipboardContext { content: s.to_owned() } } } impl ClipboardProvider for DummyClipboardContext { fn get_clipboard_contents(&mut self) -> String { self.content.clone() } fn set_clipboard_contents(&mut self, s: &str) { self.content = s.to_owned(); } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
random_line_split
clipboard_provider.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; use collections::borrow::ToOwned; use std::sync::mpsc::channel; pub trait ClipboardProvider { // blocking method to get the clipboard contents fn get_clipboard_contents(&mut self) -> String; // blocking method to set the clipboard contents fn set_clipboard_contents(&mut self, &str); } impl ClipboardProvider for ConstellationChan { fn get_clipboard_contents(&mut self) -> String { let (tx, rx) = channel(); self.0.send(ConstellationMsg::GetClipboardContents(tx)).unwrap(); rx.recv().unwrap() } fn
(&mut self, _: &str) { panic!("not yet implemented"); } } pub struct DummyClipboardContext { content: String } impl DummyClipboardContext { pub fn new(s: &str) -> DummyClipboardContext { DummyClipboardContext { content: s.to_owned() } } } impl ClipboardProvider for DummyClipboardContext { fn get_clipboard_contents(&mut self) -> String { self.content.clone() } fn set_clipboard_contents(&mut self, s: &str) { self.content = s.to_owned(); } }
set_clipboard_contents
identifier_name
clipboard_provider.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; use collections::borrow::ToOwned; use std::sync::mpsc::channel; pub trait ClipboardProvider { // blocking method to get the clipboard contents fn get_clipboard_contents(&mut self) -> String; // blocking method to set the clipboard contents fn set_clipboard_contents(&mut self, &str); } impl ClipboardProvider for ConstellationChan { fn get_clipboard_contents(&mut self) -> String { let (tx, rx) = channel(); self.0.send(ConstellationMsg::GetClipboardContents(tx)).unwrap(); rx.recv().unwrap() } fn set_clipboard_contents(&mut self, _: &str)
} pub struct DummyClipboardContext { content: String } impl DummyClipboardContext { pub fn new(s: &str) -> DummyClipboardContext { DummyClipboardContext { content: s.to_owned() } } } impl ClipboardProvider for DummyClipboardContext { fn get_clipboard_contents(&mut self) -> String { self.content.clone() } fn set_clipboard_contents(&mut self, s: &str) { self.content = s.to_owned(); } }
{ panic!("not yet implemented"); }
identifier_body
DbvsFreq-Ampde0.1v-2huequitos.py
#!/usr/bin/env python2.7 import numpy as np
Freq=np.array([30,40,45,50,53,55,60,65,70,80,90,95,98,100,110,120]) Db=np.array([70.5,78.6,83.2,88.4,87.5,86.7,85.2,83.9,85.1,88,95.7,100.4,100.4,99.2,94.7,94.9]) plt.xlabel('Frecuencia') plt.ylabel('Decibel') plt.title('DecibelvsFreq a 0.1volts') #for i in range(len(Freq)): # plt.text(Freq[i],Db[i], r'$Freq=%f, \ Db=%f$' % (Freq[i], Db[i])) plt.axis([0, 330, 50, 130]) plt.plot(Freq,Db,'bo',Freq,Db,'k') plt.grid(True) plt.show()
import matplotlib.pyplot as plt
random_line_split
FieldChips.stories.tsx
/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { ExtendComponentsThemeProvider } from '@looker/components-providers' import type { Story } from '@storybook/react/types-6-0' import React, { useState } from 'react' import { Grid, SpaceVertical } from '../../../Layout' import { Paragraph } from '../../../Text' import { defaultArgTypes as argTypes } from '../../../../../../apps/storybook/src/defaultArgTypes' import type { FieldChipsProps } from './FieldChips' import { FieldChips } from './FieldChips' export default { argTypes, component: FieldChips, title: 'FieldChips', } const Template: Story< FieldChipsProps & { externalLabel: boolean; initialValues: string[] } > = ({ externalLabel = true, initialValues, ...args }) => { const [values, setValues] = useState<string[]>(initialValues || ['apples']) return ( <ExtendComponentsThemeProvider themeCustomizations={{ defaults: { externalLabel } }} > <FieldChips {...args} values={values} onChange={setValues} /> </ExtendComponentsThemeProvider> ) } export const Basic = Template.bind({}) Basic.args = { label: 'Basic' } export const FloatingLabel = Template.bind({}) FloatingLabel.args = { externalLabel: false, label: 'Floating Label', } export const Truncate = Template.bind({}) Truncate.args = { ...Basic.args, initialValues: ['A very long token that will truncate'], label: 'Truncate', width: 250, } export const Overflow = Template.bind({}) Overflow.args = { ...Basic.args, initialValues: [ 'California', 'Wyoming', 'Nevada', 'Wisconsin', 'Mississippi', 'Missouri', 'New York', 'New Jersey', ], label: 'Overflow', maxHeight: 145, width: 200, } export const AutoResize = Template.bind({}) AutoResize.args = { ...Basic.args, autoResize: true, label: 'Auto Resize', maxWidth: '50vw', placeholder: 'Auto Resize', } export const AutoResizeFloatingLabel = Template.bind({}) AutoResizeFloatingLabel.args = { ...AutoResize.args, externalLabel: false, placeholder: 'Auto Resize', } export const FieldChipOptions = () => { const [values, setValues] = useState<string[]>(['apples']) const handleChange = (vals: string[]) => setValues(vals) return ( <Grid columns={1}> <FieldChips label="FieldChip's Label" onChange={handleChange} values={values} /> <FieldChips detail="5/50" description="this is a description" label="FieldChip's Label" onChange={handleChange} values={values} /> <FieldChips label="FieldChip's Label" onChange={handleChange}
/> </Grid> ) } FieldChipOptions.parameters = { storyshots: { disable: true }, } export const Controlled = () => { const [values, setValues] = useState<string[]>(['bananas']) const [inputValue, setInputValue] = useState('oranges') const handleChange = (vals: string[]) => setValues(vals) const handleInputChange = (value: string) => setInputValue(value) return ( <FieldChips values={values} inputValue={inputValue} onChange={handleChange} onInputChange={handleInputChange} summary="summary" /> ) } Controlled.parameters = { storyshots: { disable: true }, } const emailValidator = /^(([^<>()[\]\\.,:\s@"]+(\.[^<>()[\]\\.,:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ export const ValidationDuplicate = () => { const [values, setValues] = useState<string[]>(['bob@internet.com']) const [invalid, setInvalid] = useState('') const [duplicate, setDuplicate] = useState('') const handleChange = (vals: string[]) => { setInvalid('') setDuplicate('') setValues(vals) } const handleInvalid = (values: string[]) => setInvalid(`Invalid email: ${values.join(', ')}`) const handleDuplicate = (values: string[]) => setDuplicate(`Duplicate email: ${values.join(', ')}`) return ( <SpaceVertical> <FieldChips values={values} onChange={handleChange} placeholder="Email validation" validate={(val: string) => emailValidator.test(val)} onValidationFail={handleInvalid} onDuplicate={handleDuplicate} /> <Paragraph> {invalid} {duplicate} </Paragraph> </SpaceVertical> ) } ValidationDuplicate.parameters = { storyshots: { disable: true }, }
validationMessage={{ message: 'This is an error', type: 'error', }} values={values}
random_line_split
index.d.ts
// Type definitions for non-npm package amap-js-api-scale 1.4 // Project: https://lbs.amap.com/api/javascript-api/reference/map-control#AMap.Scale // Definitions by: breeze9527 <https://github.com/breeze9527> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// <reference types="amap-js-api" /> declare namespace AMap { namespace Scale { interface EventMap { show: Event<'show'>; hide: Event<'hide'>; } type Position = 'LT' | 'RT' | 'LB' | 'RB'; interface Options { /** * 控件停靠位置 * LT:左上角; * RT:右上角; * LB:左下角; * RB:右下角; * 默认位置:LB */ position?: Position | undefined; /** * 是否可见 */ visible?: boolean | undefined; /** * 相对于地图容器左上角的偏移量 */ offset?: Pixel | undefined; } } /** * 比例尺插件 */ class Scale extends EventEmitter { constructor(options?: Scale.Options); /**
控件停靠位置 */ position: Scale.Position; /** * 相对于地图容器左上角的偏移量 */ offset: Pixel; /** * 是否可见 */ visible: boolean; /** * 显示比例尺 */ show(): void; /** * 隐藏比例尺 */ hide(): void; } }
*
identifier_name
index.d.ts
// Type definitions for non-npm package amap-js-api-scale 1.4 // Project: https://lbs.amap.com/api/javascript-api/reference/map-control#AMap.Scale // Definitions by: breeze9527 <https://github.com/breeze9527> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// <reference types="amap-js-api" /> declare namespace AMap { namespace Scale { interface EventMap { show: Event<'show'>; hide: Event<'hide'>; } type Position = 'LT' | 'RT' | 'LB' | 'RB'; interface Options { /** * 控件停靠位置 * LT:左上角; * RT:右上角; * LB:左下角; * RB:右下角; * 默认位置:LB */ position?: Position | undefined; /** * 是否可见 */ visible?: boolean | undefined; /** * 相对于地图容器左上角的偏移量 */ offset?: Pixel | undefined; } }
/** * 比例尺插件 */ class Scale extends EventEmitter { constructor(options?: Scale.Options); /** * 控件停靠位置 */ position: Scale.Position; /** * 相对于地图容器左上角的偏移量 */ offset: Pixel; /** * 是否可见 */ visible: boolean; /** * 显示比例尺 */ show(): void; /** * 隐藏比例尺 */ hide(): void; } }
random_line_split
__init__.py
"""The StarLine component.""" import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.core import Config, HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .account import StarlineAccount from .const import ( DOMAIN, PLATFORMS, SERVICE_UPDATE_STATE, SERVICE_SET_SCAN_INTERVAL, CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL, ) async def async_setup(hass: HomeAssistant, config: Config) -> bool: """Set up configured StarLine.""" return True async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up the StarLine device from a config entry.""" account = StarlineAccount(hass, config_entry) await account.update() if not account.api.available: raise ConfigEntryNotReady if DOMAIN not in hass.data: hass.data[DOMAIN] = {} hass.data[DOMAIN][config_entry.entry_id] = account device_registry = await hass.helpers.device_registry.async_get_registry() for device in account.api.devices.values(): device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, **account.device_info(device) ) for domain in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, domain) ) async def async_set_scan_interval(call): """Service for set scan interval.""" options = dict(config_entry.options) options[CONF_SCAN_INTERVAL] = call.data[CONF_SCAN_INTERVAL] hass.config_entries.async_update_entry(entry=config_entry, options=options) hass.services.async_register(DOMAIN, SERVICE_UPDATE_STATE, account.update) hass.services.async_register( DOMAIN, SERVICE_SET_SCAN_INTERVAL, async_set_scan_interval, schema=vol.Schema( { vol.Required(CONF_SCAN_INTERVAL): vol.All( vol.Coerce(int), vol.Range(min=10) ) } ), ) config_entry.add_update_listener(async_options_updated) await async_options_updated(hass, config_entry) return True async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Unload a config entry.""" for domain in PLATFORMS: await hass.config_entries.async_forward_entry_unload(config_entry, domain) account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] account.unload() return True async def async_options_updated(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Triggered by config entry options updates.""" account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] scan_interval = config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) account.set_update_interval(scan_interval)
identifier_body
__init__.py
"""The StarLine component.""" import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.core import Config, HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .account import StarlineAccount from .const import ( DOMAIN, PLATFORMS, SERVICE_UPDATE_STATE, SERVICE_SET_SCAN_INTERVAL, CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL, ) async def async_setup(hass: HomeAssistant, config: Config) -> bool: """Set up configured StarLine.""" return True async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up the StarLine device from a config entry.""" account = StarlineAccount(hass, config_entry) await account.update() if not account.api.available: raise ConfigEntryNotReady if DOMAIN not in hass.data: hass.data[DOMAIN] = {} hass.data[DOMAIN][config_entry.entry_id] = account device_registry = await hass.helpers.device_registry.async_get_registry() for device in account.api.devices.values(): device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, **account.device_info(device) ) for domain in PLATFORMS:
async def async_set_scan_interval(call): """Service for set scan interval.""" options = dict(config_entry.options) options[CONF_SCAN_INTERVAL] = call.data[CONF_SCAN_INTERVAL] hass.config_entries.async_update_entry(entry=config_entry, options=options) hass.services.async_register(DOMAIN, SERVICE_UPDATE_STATE, account.update) hass.services.async_register( DOMAIN, SERVICE_SET_SCAN_INTERVAL, async_set_scan_interval, schema=vol.Schema( { vol.Required(CONF_SCAN_INTERVAL): vol.All( vol.Coerce(int), vol.Range(min=10) ) } ), ) config_entry.add_update_listener(async_options_updated) await async_options_updated(hass, config_entry) return True async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Unload a config entry.""" for domain in PLATFORMS: await hass.config_entries.async_forward_entry_unload(config_entry, domain) account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] account.unload() return True async def async_options_updated(hass: HomeAssistant, config_entry: ConfigEntry) -> None: """Triggered by config entry options updates.""" account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] scan_interval = config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) account.set_update_interval(scan_interval)
hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, domain) )
conditional_block
__init__.py
"""The StarLine component.""" import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.core import Config, HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .account import StarlineAccount from .const import ( DOMAIN, PLATFORMS, SERVICE_UPDATE_STATE, SERVICE_SET_SCAN_INTERVAL, CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL, ) async def async_setup(hass: HomeAssistant, config: Config) -> bool: """Set up configured StarLine.""" return True async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up the StarLine device from a config entry.""" account = StarlineAccount(hass, config_entry) await account.update() if not account.api.available: raise ConfigEntryNotReady if DOMAIN not in hass.data: hass.data[DOMAIN] = {} hass.data[DOMAIN][config_entry.entry_id] = account device_registry = await hass.helpers.device_registry.async_get_registry() for device in account.api.devices.values(): device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, **account.device_info(device) ) for domain in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, domain) ) async def async_set_scan_interval(call): """Service for set scan interval.""" options = dict(config_entry.options) options[CONF_SCAN_INTERVAL] = call.data[CONF_SCAN_INTERVAL] hass.config_entries.async_update_entry(entry=config_entry, options=options) hass.services.async_register(DOMAIN, SERVICE_UPDATE_STATE, account.update) hass.services.async_register( DOMAIN, SERVICE_SET_SCAN_INTERVAL, async_set_scan_interval, schema=vol.Schema( { vol.Required(CONF_SCAN_INTERVAL): vol.All( vol.Coerce(int), vol.Range(min=10) ) } ), ) config_entry.add_update_listener(async_options_updated) await async_options_updated(hass, config_entry) return True
await hass.config_entries.async_forward_entry_unload(config_entry, domain) account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] account.unload() return True async def async_options_updated(hass: HomeAssistant, config_entry: ConfigEntry) -> None: """Triggered by config entry options updates.""" account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] scan_interval = config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) account.set_update_interval(scan_interval)
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Unload a config entry.""" for domain in PLATFORMS:
random_line_split
__init__.py
"""The StarLine component.""" import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.core import Config, HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .account import StarlineAccount from .const import ( DOMAIN, PLATFORMS, SERVICE_UPDATE_STATE, SERVICE_SET_SCAN_INTERVAL, CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL, ) async def async_setup(hass: HomeAssistant, config: Config) -> bool: """Set up configured StarLine.""" return True async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up the StarLine device from a config entry.""" account = StarlineAccount(hass, config_entry) await account.update() if not account.api.available: raise ConfigEntryNotReady if DOMAIN not in hass.data: hass.data[DOMAIN] = {} hass.data[DOMAIN][config_entry.entry_id] = account device_registry = await hass.helpers.device_registry.async_get_registry() for device in account.api.devices.values(): device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, **account.device_info(device) ) for domain in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, domain) ) async def async_set_scan_interval(call): """Service for set scan interval.""" options = dict(config_entry.options) options[CONF_SCAN_INTERVAL] = call.data[CONF_SCAN_INTERVAL] hass.config_entries.async_update_entry(entry=config_entry, options=options) hass.services.async_register(DOMAIN, SERVICE_UPDATE_STATE, account.update) hass.services.async_register( DOMAIN, SERVICE_SET_SCAN_INTERVAL, async_set_scan_interval, schema=vol.Schema( { vol.Required(CONF_SCAN_INTERVAL): vol.All( vol.Coerce(int), vol.Range(min=10) ) } ), ) config_entry.add_update_listener(async_options_updated) await async_options_updated(hass, config_entry) return True async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Unload a config entry.""" for domain in PLATFORMS: await hass.config_entries.async_forward_entry_unload(config_entry, domain) account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] account.unload() return True async def
(hass: HomeAssistant, config_entry: ConfigEntry) -> None: """Triggered by config entry options updates.""" account: StarlineAccount = hass.data[DOMAIN][config_entry.entry_id] scan_interval = config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) account.set_update_interval(scan_interval)
async_options_updated
identifier_name
lists.py
""" This file contains code for working on lists and dictionaries. """ def moreThanOne(dict, key): """ Checks if a key in a dictionary has a value more than one. Arguments: dict -- the dictionary key -- the key Returns: True if the key exists in the dictionary and the value is at least one, otherwise false """ return key in dict and dict[key] > 0 def anyMoreThanOne(dict, keys): """ Checks if any of a list of keys in a dictionary has a value more than one. Arguments: dict -- the dictionary keys -- the keys Returns: True if any key exists in the dictionary and the value is at least one, otherwise false """ for key in keys: if key in dict and dict[key] > 0: return True return False def makeUnique(list): """ Removes duplicates from a list. """ u = [] for l in list:
return u def alphabetical(lst): """ Sorts a list of tuples in reverse alphabetical order by the first key in the tuple. Arguments: lst -- the list to sort Returns: the sorted list """ return list(reversed(sorted(lst, key=lambda x: x[0])))
if not l in u: u.append(l)
conditional_block
lists.py
""" This file contains code for working on lists and dictionaries. """ def moreThanOne(dict, key): """ Checks if a key in a dictionary has a value more than one. Arguments: dict -- the dictionary key -- the key Returns: True if the key exists in the dictionary and the value is at least one, otherwise false """ return key in dict and dict[key] > 0 def anyMoreThanOne(dict, keys): """ Checks if any of a list of keys in a dictionary has a value more than one. Arguments: dict -- the dictionary keys -- the keys Returns: True if any key exists in the dictionary and the value is at least one, otherwise false """ for key in keys: if key in dict and dict[key] > 0: return True return False def makeUnique(list): """ Removes duplicates from a list. """ u = [] for l in list: if not l in u: u.append(l) return u def
(lst): """ Sorts a list of tuples in reverse alphabetical order by the first key in the tuple. Arguments: lst -- the list to sort Returns: the sorted list """ return list(reversed(sorted(lst, key=lambda x: x[0])))
alphabetical
identifier_name
lists.py
""" This file contains code for working on lists and dictionaries. """ def moreThanOne(dict, key): """ Checks if a key in a dictionary has a value more than one. Arguments: dict -- the dictionary key -- the key Returns: True if the key exists in the dictionary and the value is at least one, otherwise false """ return key in dict and dict[key] > 0 def anyMoreThanOne(dict, keys): """ Checks if any of a list of keys in a dictionary has a value more than one. Arguments: dict -- the dictionary keys -- the keys Returns: True if any key exists in the dictionary and the value is at least one, otherwise false """ for key in keys: if key in dict and dict[key] > 0: return True
for l in list: if not l in u: u.append(l) return u def alphabetical(lst): """ Sorts a list of tuples in reverse alphabetical order by the first key in the tuple. Arguments: lst -- the list to sort Returns: the sorted list """ return list(reversed(sorted(lst, key=lambda x: x[0])))
return False def makeUnique(list): """ Removes duplicates from a list. """ u = []
random_line_split
lists.py
""" This file contains code for working on lists and dictionaries. """ def moreThanOne(dict, key): """ Checks if a key in a dictionary has a value more than one. Arguments: dict -- the dictionary key -- the key Returns: True if the key exists in the dictionary and the value is at least one, otherwise false """ return key in dict and dict[key] > 0 def anyMoreThanOne(dict, keys):
def makeUnique(list): """ Removes duplicates from a list. """ u = [] for l in list: if not l in u: u.append(l) return u def alphabetical(lst): """ Sorts a list of tuples in reverse alphabetical order by the first key in the tuple. Arguments: lst -- the list to sort Returns: the sorted list """ return list(reversed(sorted(lst, key=lambda x: x[0])))
""" Checks if any of a list of keys in a dictionary has a value more than one. Arguments: dict -- the dictionary keys -- the keys Returns: True if any key exists in the dictionary and the value is at least one, otherwise false """ for key in keys: if key in dict and dict[key] > 0: return True return False
identifier_body
console.py
#!/usr/bin/python # Console import sys, os, time, subprocess def MCS(): return subprocess.Popen(['python', 'mcs.py']) def color(text, color): if color == 0: color = "\033[0m" if color == 1: color = "\033[94m" if color == 2: color = "\033[92m" if color == 3: color = "\033[91m" if color == 4: color = "\033[93m" return color+text+"\033[0m" def showMenu(): print("\033[H\033[J", end="") print("== Music Control System v0.1 ==") print("= =") print("= {} MCS Time {} =".format(color("[7]",1), color("[8]",3))) print("= {} MCS Auto {} =".format(color("[4]",1), color("[5]",3))) print("= {} MCS EDT {} =".format(color("[1]",1), color("[2]",3))) print("= =") print("========= Informations ========") print("= =") print("= =") print("= =") print("===============================") def main(): # Old hack (TODO) class main: def poll(): return True while 1: showMenu() command = str(input("=> ")) if command == '4': if main.poll() == None: main.terminate() main.kill() main = MCS() if command == '5':
if command == 'q': exit(0) if __name__ == "__main__": main()
if main.poll() == None: main.terminate() main.kill()
conditional_block
console.py
#!/usr/bin/python # Console import sys, os, time, subprocess def MCS(): return subprocess.Popen(['python', 'mcs.py']) def color(text, color): if color == 0: color = "\033[0m" if color == 1: color = "\033[94m" if color == 2: color = "\033[92m" if color == 3: color = "\033[91m" if color == 4: color = "\033[93m" return color+text+"\033[0m" def showMenu(): print("\033[H\033[J", end="") print("== Music Control System v0.1 ==") print("= =") print("= {} MCS Time {} =".format(color("[7]",1), color("[8]",3))) print("= {} MCS Auto {} =".format(color("[4]",1), color("[5]",3))) print("= {} MCS EDT {} =".format(color("[1]",1), color("[2]",3))) print("= =") print("========= Informations ========") print("= =") print("= =") print("= =") print("===============================") def main(): # Old hack (TODO) class main: def
(): return True while 1: showMenu() command = str(input("=> ")) if command == '4': if main.poll() == None: main.terminate() main.kill() main = MCS() if command == '5': if main.poll() == None: main.terminate() main.kill() if command == 'q': exit(0) if __name__ == "__main__": main()
poll
identifier_name
console.py
#!/usr/bin/python # Console import sys, os, time, subprocess def MCS(): return subprocess.Popen(['python', 'mcs.py'])
if color == 0: color = "\033[0m" if color == 1: color = "\033[94m" if color == 2: color = "\033[92m" if color == 3: color = "\033[91m" if color == 4: color = "\033[93m" return color+text+"\033[0m" def showMenu(): print("\033[H\033[J", end="") print("== Music Control System v0.1 ==") print("= =") print("= {} MCS Time {} =".format(color("[7]",1), color("[8]",3))) print("= {} MCS Auto {} =".format(color("[4]",1), color("[5]",3))) print("= {} MCS EDT {} =".format(color("[1]",1), color("[2]",3))) print("= =") print("========= Informations ========") print("= =") print("= =") print("= =") print("===============================") def main(): # Old hack (TODO) class main: def poll(): return True while 1: showMenu() command = str(input("=> ")) if command == '4': if main.poll() == None: main.terminate() main.kill() main = MCS() if command == '5': if main.poll() == None: main.terminate() main.kill() if command == 'q': exit(0) if __name__ == "__main__": main()
def color(text, color):
random_line_split
console.py
#!/usr/bin/python # Console import sys, os, time, subprocess def MCS(): return subprocess.Popen(['python', 'mcs.py']) def color(text, color): if color == 0: color = "\033[0m" if color == 1: color = "\033[94m" if color == 2: color = "\033[92m" if color == 3: color = "\033[91m" if color == 4: color = "\033[93m" return color+text+"\033[0m" def showMenu(): print("\033[H\033[J", end="") print("== Music Control System v0.1 ==") print("= =") print("= {} MCS Time {} =".format(color("[7]",1), color("[8]",3))) print("= {} MCS Auto {} =".format(color("[4]",1), color("[5]",3))) print("= {} MCS EDT {} =".format(color("[1]",1), color("[2]",3))) print("= =") print("========= Informations ========") print("= =") print("= =") print("= =") print("===============================") def main(): # Old hack (TODO) class main:
while 1: showMenu() command = str(input("=> ")) if command == '4': if main.poll() == None: main.terminate() main.kill() main = MCS() if command == '5': if main.poll() == None: main.terminate() main.kill() if command == 'q': exit(0) if __name__ == "__main__": main()
def poll(): return True
identifier_body
test_nis.py
from test import support import unittest import sys # Skip test if nis module does not exist. nis = support.import_module('nis') class NisTests(unittest.TestCase): def test_maps(self):
if __name__ == '__main__': unittest.main()
try: maps = nis.maps() except nis.error as msg: # NIS is probably not active, so this test isn't useful self.skipTest(str(msg)) try: # On some systems, this map is only accessible to the # super user maps.remove("passwd.adjunct.byname") except ValueError: pass done = 0 for nismap in maps: mapping = nis.cat(nismap) for k, v in mapping.items(): if not k: continue if nis.match(k, nismap) != v: self.fail("NIS match failed for key `%s' in map `%s'" % (k, nismap)) else: # just test the one key, otherwise this test could take a # very long time done = 1 break if done: break
identifier_body
test_nis.py
from test import support import unittest import sys
nis = support.import_module('nis') class NisTests(unittest.TestCase): def test_maps(self): try: maps = nis.maps() except nis.error as msg: # NIS is probably not active, so this test isn't useful self.skipTest(str(msg)) try: # On some systems, this map is only accessible to the # super user maps.remove("passwd.adjunct.byname") except ValueError: pass done = 0 for nismap in maps: mapping = nis.cat(nismap) for k, v in mapping.items(): if not k: continue if nis.match(k, nismap) != v: self.fail("NIS match failed for key `%s' in map `%s'" % (k, nismap)) else: # just test the one key, otherwise this test could take a # very long time done = 1 break if done: break if __name__ == '__main__': unittest.main()
# Skip test if nis module does not exist.
random_line_split
test_nis.py
from test import support import unittest import sys # Skip test if nis module does not exist. nis = support.import_module('nis') class NisTests(unittest.TestCase): def test_maps(self): try: maps = nis.maps() except nis.error as msg: # NIS is probably not active, so this test isn't useful self.skipTest(str(msg)) try: # On some systems, this map is only accessible to the # super user maps.remove("passwd.adjunct.byname") except ValueError: pass done = 0 for nismap in maps:
if __name__ == '__main__': unittest.main()
mapping = nis.cat(nismap) for k, v in mapping.items(): if not k: continue if nis.match(k, nismap) != v: self.fail("NIS match failed for key `%s' in map `%s'" % (k, nismap)) else: # just test the one key, otherwise this test could take a # very long time done = 1 break if done: break
conditional_block
test_nis.py
from test import support import unittest import sys # Skip test if nis module does not exist. nis = support.import_module('nis') class NisTests(unittest.TestCase): def
(self): try: maps = nis.maps() except nis.error as msg: # NIS is probably not active, so this test isn't useful self.skipTest(str(msg)) try: # On some systems, this map is only accessible to the # super user maps.remove("passwd.adjunct.byname") except ValueError: pass done = 0 for nismap in maps: mapping = nis.cat(nismap) for k, v in mapping.items(): if not k: continue if nis.match(k, nismap) != v: self.fail("NIS match failed for key `%s' in map `%s'" % (k, nismap)) else: # just test the one key, otherwise this test could take a # very long time done = 1 break if done: break if __name__ == '__main__': unittest.main()
test_maps
identifier_name
codec.rs
// Copyright 2016 Google 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 agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::errors::*; use crate::geometry::Cube; use crate::proto; use nalgebra::{Point3, Scalar, Vector3}; use num::clamp; use std::fmt::Debug; #[derive(Clone, Debug, PartialEq, Eq)] pub enum
{ Uint8, Uint16, Float32, Float64, } impl PositionEncoding { pub fn new(bounding_cube: &Cube, resolution: f64) -> PositionEncoding { let min_bits = (bounding_cube.edge_length() / resolution).log2() as u32 + 1; match min_bits { 0..=8 => PositionEncoding::Uint8, 9..=16 => PositionEncoding::Uint16, // Capping at 24 keeps the worst resolution at ~1 mm for an edge length of ~8389 km. 17..=24 => PositionEncoding::Float32, _ => PositionEncoding::Float64, } } // TODO(sirver): Returning a Result here makes this function more expensive than needed - since // we require stack space for the full Result. This should be fixable to moving to failure. pub fn from_proto(proto: proto::PositionEncoding) -> Result<Self> { match proto { proto::PositionEncoding::Uint8 => Ok(PositionEncoding::Uint8), proto::PositionEncoding::Uint16 => Ok(PositionEncoding::Uint16), proto::PositionEncoding::Float32 => Ok(PositionEncoding::Float32), proto::PositionEncoding::Float64 => Ok(PositionEncoding::Float64), proto::PositionEncoding::INVALID => Err(ErrorKind::InvalidInput( "Proto: PositionEncoding is invalid".to_string(), ) .into()), } } pub fn to_proto(&self) -> proto::PositionEncoding { match *self { PositionEncoding::Uint8 => proto::PositionEncoding::Uint8, PositionEncoding::Uint16 => proto::PositionEncoding::Uint16, PositionEncoding::Float32 => proto::PositionEncoding::Float32, PositionEncoding::Float64 => proto::PositionEncoding::Float64, } } pub fn bytes_per_coordinate(&self) -> usize { match *self { PositionEncoding::Uint8 => 1, PositionEncoding::Uint16 => 2, PositionEncoding::Float32 => 4, PositionEncoding::Float64 => 8, } } } /// The _encode and _decode functions are not methods of this type, because /// we are sometimes able to pull the match outside the inner loop. #[derive(Clone)] pub enum Encoding { Plain, ScaledToCube(Point3<f64>, f64, PositionEncoding), } /// Encode float as integer. pub fn fixpoint_encode<T>(value: f64, min: f64, edge_length: f64) -> T where T: num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>, { let value = clamp((value - min) / edge_length, 0., 1.) * nalgebra::convert::<T, f64>(T::max_value()); nalgebra::try_convert(value).unwrap() } /// Encode float as f32 or f64 unit interval float. pub fn _encode<T>(value: f64, min: f64, edge_length: f64) -> T where T: simba::scalar::SubsetOf<f64>, { nalgebra::try_convert(clamp((value - min) / edge_length, 0., 1.)).unwrap() } pub fn vec3_fixpoint_encode<T>( value: &Point3<f64>, min: &Point3<f64>, edge_length: f64, ) -> Vector3<T> where T: Scalar + num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>, { let scale: f64 = nalgebra::convert(T::max_value()); let value = clamp_elementwise((value - min) / edge_length, 0.0, 1.0); nalgebra::try_convert(scale * value).unwrap() } pub fn vec3_encode<T>(value: &Point3<f64>, min: &Point3<f64>, edge_length: f64) -> Vector3<T> where T: Scalar + simba::scalar::SubsetOf<f64>, { let value = clamp_elementwise((value - min) / edge_length, 0.0, 1.0); nalgebra::try_convert(value).unwrap() } /// Decode integer as float. pub fn fixpoint_decode<T>(value: T, min: f64, edge_length: f64) -> f64 where T: num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>, { let max: f64 = nalgebra::convert(T::max_value()); let v: f64 = nalgebra::convert(value); (v / max).mul_add(edge_length, min) } /// Decode f32 or f64 unit interval float as f64. pub fn decode<T>(value: T, min: f64, edge_length: f64) -> f64 where T: simba::scalar::SubsetOf<f64>, { nalgebra::convert::<T, f64>(value).mul_add(edge_length, min) } // Careful: num's (or nalgebra's) clamp accepts Vector3 too, but does not work elementwise like this fn clamp_elementwise(value: Vector3<f64>, lower: f64, upper: f64) -> Vector3<f64> { Vector3::new( clamp(value.x, lower, upper), clamp(value.y, lower, upper), clamp(value.z, lower, upper), ) } #[cfg(test)] mod tests { use super::*; #[test] fn plain_scalar() { let value = 41.33333; let min = 40.0; let edge_length = 2.0; let value_f32 = _encode::<f32>(value, min, edge_length); let value_f32_decoded = decode(value_f32, min, edge_length); // We could use the approx crate here and elsewhere assert!( (value_f32_decoded - value).abs() < 1e-7, "Reconstructed from f32: {}, original: {}", value_f32_decoded, value ); let value_f64 = _encode::<f64>(value, min, edge_length); let value_f64_decoded = decode(value_f64, min, edge_length); assert!( (value_f64_decoded - value).abs() < 1e-14, "Reconstructed from f64: {}, original: {}", value_f64_decoded, value ); } #[test] fn fixpoint_scalar() { let value = 41.33333; let min = 40.0; let edge_length = 2.0; let value_u8 = fixpoint_encode::<u8>(value, min, edge_length); let value_u8_decoded = fixpoint_decode(value_u8, min, edge_length); assert!( (value_u8_decoded - value).abs() < 1e-2, "Reconstructed from u8: {}, original: {}", value_u8_decoded, value ); let value_u16 = fixpoint_encode::<u16>(value, min, edge_length); let value_u16_decoded = fixpoint_decode(value_u16, min, edge_length); assert!( (value_u16_decoded - value).abs() < 1e-4, "Reconstructed from u16: {}, original: {}", value_u16_decoded, value ); let value_u32 = fixpoint_encode::<u32>(value, min, edge_length); let value_u32_decoded = fixpoint_decode(value_u32, min, edge_length); assert!( (value_u32_decoded - value).abs() < 1e-7, "Reconstructed from u32: {}, original: {}", value_u32_decoded, value ); } }
PositionEncoding
identifier_name
codec.rs
// Copyright 2016 Google 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 agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::errors::*; use crate::geometry::Cube; use crate::proto; use nalgebra::{Point3, Scalar, Vector3}; use num::clamp; use std::fmt::Debug; #[derive(Clone, Debug, PartialEq, Eq)] pub enum PositionEncoding { Uint8, Uint16, Float32, Float64, } impl PositionEncoding { pub fn new(bounding_cube: &Cube, resolution: f64) -> PositionEncoding { let min_bits = (bounding_cube.edge_length() / resolution).log2() as u32 + 1; match min_bits { 0..=8 => PositionEncoding::Uint8, 9..=16 => PositionEncoding::Uint16,
// Capping at 24 keeps the worst resolution at ~1 mm for an edge length of ~8389 km. 17..=24 => PositionEncoding::Float32, _ => PositionEncoding::Float64, } } // TODO(sirver): Returning a Result here makes this function more expensive than needed - since // we require stack space for the full Result. This should be fixable to moving to failure. pub fn from_proto(proto: proto::PositionEncoding) -> Result<Self> { match proto { proto::PositionEncoding::Uint8 => Ok(PositionEncoding::Uint8), proto::PositionEncoding::Uint16 => Ok(PositionEncoding::Uint16), proto::PositionEncoding::Float32 => Ok(PositionEncoding::Float32), proto::PositionEncoding::Float64 => Ok(PositionEncoding::Float64), proto::PositionEncoding::INVALID => Err(ErrorKind::InvalidInput( "Proto: PositionEncoding is invalid".to_string(), ) .into()), } } pub fn to_proto(&self) -> proto::PositionEncoding { match *self { PositionEncoding::Uint8 => proto::PositionEncoding::Uint8, PositionEncoding::Uint16 => proto::PositionEncoding::Uint16, PositionEncoding::Float32 => proto::PositionEncoding::Float32, PositionEncoding::Float64 => proto::PositionEncoding::Float64, } } pub fn bytes_per_coordinate(&self) -> usize { match *self { PositionEncoding::Uint8 => 1, PositionEncoding::Uint16 => 2, PositionEncoding::Float32 => 4, PositionEncoding::Float64 => 8, } } } /// The _encode and _decode functions are not methods of this type, because /// we are sometimes able to pull the match outside the inner loop. #[derive(Clone)] pub enum Encoding { Plain, ScaledToCube(Point3<f64>, f64, PositionEncoding), } /// Encode float as integer. pub fn fixpoint_encode<T>(value: f64, min: f64, edge_length: f64) -> T where T: num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>, { let value = clamp((value - min) / edge_length, 0., 1.) * nalgebra::convert::<T, f64>(T::max_value()); nalgebra::try_convert(value).unwrap() } /// Encode float as f32 or f64 unit interval float. pub fn _encode<T>(value: f64, min: f64, edge_length: f64) -> T where T: simba::scalar::SubsetOf<f64>, { nalgebra::try_convert(clamp((value - min) / edge_length, 0., 1.)).unwrap() } pub fn vec3_fixpoint_encode<T>( value: &Point3<f64>, min: &Point3<f64>, edge_length: f64, ) -> Vector3<T> where T: Scalar + num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>, { let scale: f64 = nalgebra::convert(T::max_value()); let value = clamp_elementwise((value - min) / edge_length, 0.0, 1.0); nalgebra::try_convert(scale * value).unwrap() } pub fn vec3_encode<T>(value: &Point3<f64>, min: &Point3<f64>, edge_length: f64) -> Vector3<T> where T: Scalar + simba::scalar::SubsetOf<f64>, { let value = clamp_elementwise((value - min) / edge_length, 0.0, 1.0); nalgebra::try_convert(value).unwrap() } /// Decode integer as float. pub fn fixpoint_decode<T>(value: T, min: f64, edge_length: f64) -> f64 where T: num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>, { let max: f64 = nalgebra::convert(T::max_value()); let v: f64 = nalgebra::convert(value); (v / max).mul_add(edge_length, min) } /// Decode f32 or f64 unit interval float as f64. pub fn decode<T>(value: T, min: f64, edge_length: f64) -> f64 where T: simba::scalar::SubsetOf<f64>, { nalgebra::convert::<T, f64>(value).mul_add(edge_length, min) } // Careful: num's (or nalgebra's) clamp accepts Vector3 too, but does not work elementwise like this fn clamp_elementwise(value: Vector3<f64>, lower: f64, upper: f64) -> Vector3<f64> { Vector3::new( clamp(value.x, lower, upper), clamp(value.y, lower, upper), clamp(value.z, lower, upper), ) } #[cfg(test)] mod tests { use super::*; #[test] fn plain_scalar() { let value = 41.33333; let min = 40.0; let edge_length = 2.0; let value_f32 = _encode::<f32>(value, min, edge_length); let value_f32_decoded = decode(value_f32, min, edge_length); // We could use the approx crate here and elsewhere assert!( (value_f32_decoded - value).abs() < 1e-7, "Reconstructed from f32: {}, original: {}", value_f32_decoded, value ); let value_f64 = _encode::<f64>(value, min, edge_length); let value_f64_decoded = decode(value_f64, min, edge_length); assert!( (value_f64_decoded - value).abs() < 1e-14, "Reconstructed from f64: {}, original: {}", value_f64_decoded, value ); } #[test] fn fixpoint_scalar() { let value = 41.33333; let min = 40.0; let edge_length = 2.0; let value_u8 = fixpoint_encode::<u8>(value, min, edge_length); let value_u8_decoded = fixpoint_decode(value_u8, min, edge_length); assert!( (value_u8_decoded - value).abs() < 1e-2, "Reconstructed from u8: {}, original: {}", value_u8_decoded, value ); let value_u16 = fixpoint_encode::<u16>(value, min, edge_length); let value_u16_decoded = fixpoint_decode(value_u16, min, edge_length); assert!( (value_u16_decoded - value).abs() < 1e-4, "Reconstructed from u16: {}, original: {}", value_u16_decoded, value ); let value_u32 = fixpoint_encode::<u32>(value, min, edge_length); let value_u32_decoded = fixpoint_decode(value_u32, min, edge_length); assert!( (value_u32_decoded - value).abs() < 1e-7, "Reconstructed from u32: {}, original: {}", value_u32_decoded, value ); } }
random_line_split
lib.rs
#![cfg_attr(feature = "nightly", feature(test))] #![feature(nll, try_trait)] #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; #[macro_use] extern crate bitflags; extern crate syntax; #[macro_use] extern crate derive_more; extern crate rls_span; #[macro_use] mod testutils; #[macro_use] mod util; mod ast; mod ast_types; mod codecleaner; mod codeiter; mod core; mod fileres; mod matchers; #[cfg(feature = "metadata")] mod metadata; mod nameres; mod primitive; mod project_model; mod scopes; mod snippets; mod typeinf;
complete_from_file, complete_fully_qualified_name, find_definition, is_use_stmt, to_coords, to_point, }; pub use core::{ BytePos, ByteRange, Coordinate, FileCache, FileLoader, Location, Match, MatchType, Session, }; pub use primitive::PrimKind; pub use project_model::ProjectModelProvider; pub use snippets::snippet_for_match; pub use util::expand_ident; pub use util::{get_rust_src_path, RustSrcPathError}; #[cfg(all(feature = "nightly", test))] mod benches;
pub use ast_types::PathSearch; pub use core::{
random_line_split
class-impl-very-parameterized-trait.rs
// Copyright 2012-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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cmp; #[deriving(Show)] enum cat_type { tuxedo, tabby, tortoiseshell } impl cmp::PartialEq for cat_type { fn eq(&self, other: &cat_type) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &cat_type) -> bool { !(*self).eq(other) } } // Very silly -- this just returns the value of the name field // for any int value that's less than the meows field // ok: T should be in scope when resolving the trait ref for map struct cat<T> { // Yes, you can have negative meows meows : int, how_hungry : int, name : T, } impl<T> cat<T> { pub fn speak(&mut self) { self.meow(); } pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } fn len(&self) -> uint { self.meows as uint } fn is_empty(&self) -> bool { self.meows == 0 } fn clear(&mut self) {} fn contains_key(&self, k: &int) -> bool
fn find(&self, k: &int) -> Option<&T> { if *k <= self.meows { Some(&self.name) } else { None } } fn insert(&mut self, k: int, _: T) -> bool { self.meows += k; true } fn find_mut(&mut self, _k: &int) -> Option<&mut T> { panic!() } fn remove(&mut self, k: &int) -> bool { if self.find(k).is_some() { self.meows -= *k; true } else { false } } fn pop(&mut self, _k: &int) -> Option<T> { panic!() } fn swap(&mut self, _k: int, _v: T) -> Option<T> { panic!() } } impl<T> cat<T> { pub fn get(&self, k: &int) -> &T { match self.find(k) { Some(v) => { v } None => { panic!("epic fail"); } } } pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> { cat{meows: in_x, how_hungry: in_y, name: in_name } } } impl<T> cat<T> { fn meow(&mut self) { self.meows += 1; println!("Meow {}", self.meows); if self.meows % 5 == 0 { self.how_hungry += 1; } } } pub fn main() { let mut nyan: cat<String> = cat::new(0, 2, "nyan".to_string()); for _ in range(1u, 5) { nyan.speak(); } assert!(*nyan.find(&1).unwrap() == "nyan".to_string()); assert_eq!(nyan.find(&10), None); let mut spotty: cat<cat_type> = cat::new(2, 57, cat_type::tuxedo); for _ in range(0u, 6) { spotty.speak(); } assert_eq!(spotty.len(), 8); assert!((spotty.contains_key(&2))); assert_eq!(spotty.get(&3), &cat_type::tuxedo); }
{ *k <= self.meows }
identifier_body
class-impl-very-parameterized-trait.rs
// Copyright 2012-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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cmp; #[deriving(Show)] enum cat_type { tuxedo, tabby, tortoiseshell } impl cmp::PartialEq for cat_type { fn eq(&self, other: &cat_type) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &cat_type) -> bool { !(*self).eq(other) } } // Very silly -- this just returns the value of the name field // for any int value that's less than the meows field // ok: T should be in scope when resolving the trait ref for map struct
<T> { // Yes, you can have negative meows meows : int, how_hungry : int, name : T, } impl<T> cat<T> { pub fn speak(&mut self) { self.meow(); } pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } fn len(&self) -> uint { self.meows as uint } fn is_empty(&self) -> bool { self.meows == 0 } fn clear(&mut self) {} fn contains_key(&self, k: &int) -> bool { *k <= self.meows } fn find(&self, k: &int) -> Option<&T> { if *k <= self.meows { Some(&self.name) } else { None } } fn insert(&mut self, k: int, _: T) -> bool { self.meows += k; true } fn find_mut(&mut self, _k: &int) -> Option<&mut T> { panic!() } fn remove(&mut self, k: &int) -> bool { if self.find(k).is_some() { self.meows -= *k; true } else { false } } fn pop(&mut self, _k: &int) -> Option<T> { panic!() } fn swap(&mut self, _k: int, _v: T) -> Option<T> { panic!() } } impl<T> cat<T> { pub fn get(&self, k: &int) -> &T { match self.find(k) { Some(v) => { v } None => { panic!("epic fail"); } } } pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> { cat{meows: in_x, how_hungry: in_y, name: in_name } } } impl<T> cat<T> { fn meow(&mut self) { self.meows += 1; println!("Meow {}", self.meows); if self.meows % 5 == 0 { self.how_hungry += 1; } } } pub fn main() { let mut nyan: cat<String> = cat::new(0, 2, "nyan".to_string()); for _ in range(1u, 5) { nyan.speak(); } assert!(*nyan.find(&1).unwrap() == "nyan".to_string()); assert_eq!(nyan.find(&10), None); let mut spotty: cat<cat_type> = cat::new(2, 57, cat_type::tuxedo); for _ in range(0u, 6) { spotty.speak(); } assert_eq!(spotty.len(), 8); assert!((spotty.contains_key(&2))); assert_eq!(spotty.get(&3), &cat_type::tuxedo); }
cat
identifier_name
class-impl-very-parameterized-trait.rs
// Copyright 2012-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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cmp; #[deriving(Show)] enum cat_type { tuxedo, tabby, tortoiseshell } impl cmp::PartialEq for cat_type { fn eq(&self, other: &cat_type) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &cat_type) -> bool { !(*self).eq(other) } } // Very silly -- this just returns the value of the name field // for any int value that's less than the meows field // ok: T should be in scope when resolving the trait ref for map struct cat<T> { // Yes, you can have negative meows meows : int, how_hungry : int, name : T, } impl<T> cat<T> { pub fn speak(&mut self) { self.meow(); } pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } fn len(&self) -> uint { self.meows as uint } fn is_empty(&self) -> bool { self.meows == 0 } fn clear(&mut self) {} fn contains_key(&self, k: &int) -> bool { *k <= self.meows } fn find(&self, k: &int) -> Option<&T> { if *k <= self.meows { Some(&self.name) } else { None } } fn insert(&mut self, k: int, _: T) -> bool { self.meows += k; true } fn find_mut(&mut self, _k: &int) -> Option<&mut T> { panic!() } fn remove(&mut self, k: &int) -> bool { if self.find(k).is_some() { self.meows -= *k; true } else { false } } fn pop(&mut self, _k: &int) -> Option<T> { panic!() } fn swap(&mut self, _k: int, _v: T) -> Option<T> { panic!() } } impl<T> cat<T> { pub fn get(&self, k: &int) -> &T { match self.find(k) { Some(v) => { v } None => { panic!("epic fail"); } }
pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> { cat{meows: in_x, how_hungry: in_y, name: in_name } } } impl<T> cat<T> { fn meow(&mut self) { self.meows += 1; println!("Meow {}", self.meows); if self.meows % 5 == 0 { self.how_hungry += 1; } } } pub fn main() { let mut nyan: cat<String> = cat::new(0, 2, "nyan".to_string()); for _ in range(1u, 5) { nyan.speak(); } assert!(*nyan.find(&1).unwrap() == "nyan".to_string()); assert_eq!(nyan.find(&10), None); let mut spotty: cat<cat_type> = cat::new(2, 57, cat_type::tuxedo); for _ in range(0u, 6) { spotty.speak(); } assert_eq!(spotty.len(), 8); assert!((spotty.contains_key(&2))); assert_eq!(spotty.get(&3), &cat_type::tuxedo); }
}
random_line_split
MiaoZuanScripts.py
#!/usr/bin/python #encoding=utf-8 import urllib, urllib2 import cookielib import re import time from random import random from json import dumps as json_dumps, loads as json_loads import sys reload(sys) sys.setdefaultencoding('utf-8') import os project_root_path = os.path.abspath(os.path.join(os.path.dirname(__file__))) sys.path.append(project_root_path) from logger.logger import logFactory logger = logFactory.getLogger(__name__) class
(object): """docstring for MiaoZuan""" def __init__(self, account_file): super(MiaoZuan, self).__init__() self.headers = headers = { 'User-Agent':'IOS_8.1_IPHONE5C', 'm-lng':'113.331639', 'm-ct':'2', 'm-lat':'23.158624', 'm-cw':'320', 'm-iv':'3.0.1', 'm-ch':'568', 'm-cv':'6.5.2', 'm-lt':'1', 'm-nw':'WIFI', #'Content-Type':'application/json;charset=utf-8' } self.accountList = self.get_account_List(account_file) def get_account_List(self, account_file): accountList = [] try: with open(account_file, 'r') as f: lines = f.readlines() for line in lines: user, userName, passWord, imei = line.strip('\n').split(',') accountList.append([user, userName, passWord, imei]) except Exception as e: logger.exception(e) finally: return accountList def login(self, userName, passWord, imei): postdata = urllib.urlencode({ 'UserName':userName, 'Password':passWord, 'Imei':imei }) req = urllib2.Request( url='http://service.inkey.com/api/Auth/Login', data=postdata, headers=self.headers ) cookie_support = urllib2.HTTPCookieProcessor(cookielib.CookieJar()) opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler) urllib2.install_opener(opener) try: content = urllib2.urlopen(req).read() resp_dict = json_loads(content) return resp_dict except Exception as e: logger.exception(e) return {"IsSuccess": False, "Desc": ""} def pull_SilverAdvert_List(self, categoryId): postdata = urllib.urlencode({ 'CategoryIds':categoryId }) req = urllib2.Request( url='http://service.inkey.com/api/SilverAdvert/Pull', data = postdata, headers = self.headers ) try: content = urllib2.urlopen(req).read() silverAdvert_pat = re.compile(r'"Id":(.*?),') silverAdvert_list = re.findall(silverAdvert_pat, content) logger.debug("categoryId = %s, pull_SilverAdvert_List = %s", categoryId, silverAdvert_list) except Exception as e: logger.exception(e) silverAdvert_list = [] return silverAdvert_list def viewOne_SilverAdvert_by_advertsID(self, advertsID): postdata = urllib.urlencode({ 'IsGame':"false", "Id":advertsID }) req = urllib2.Request( url='http://service.inkey.com/api/SilverAdvert/GeneratedIntegral', data = postdata, headers = self.headers ) try: content = urllib2.urlopen(req).read() logger.debug("view advert id = %s, Response from the server: %s", advertsID, content) resp_dict = json_loads(content) return resp_dict except Exception as e: logger.exception(e) return {"IsSuccess": False} def viewAll_SilverAdverts_by_categoryId(self, categoryId): silverAdsList = self.pull_SilverAdvert_List(categoryId) silverAdsList_Count = len(silverAdsList) total_data_by_categoryId = 0 result_Code = 0 result_Code_31303_count = 0 selectNum = 0 if silverAdsList_Count > 0: while True: advertsID = silverAdsList[selectNum] resp_dict = self.viewOne_SilverAdvert_by_advertsID(advertsID) selectNum += 1 if selectNum >= silverAdsList_Count: selectNum -= silverAdsList_Count if resp_dict["IsSuccess"]: total_data_by_categoryId += resp_dict["Data"] logger.debug("get %s more points", resp_dict["Data"]) elif resp_dict["Code"] == 31303: logger.debug("view advert id = %s, Response from the server: %s", advertsID, resp_dict["Desc"]) result_Code_31303_count += 1 continue elif resp_dict["Code"] == 31307 or result_Code_31303_count > silverAdsList_Count: logger.debug("Response from the server: %s", resp_dict["Desc"]) break time.sleep(12+3*random()) logger.info("categoryId = %s, total_data_by_categoryId = %s" % (categoryId, total_data_by_categoryId)) return [result_Code, total_data_by_categoryId] def get_all_silvers(self): total_data = 0 result_Code = 0 categoryIds = [-1, 1, -2, 2, -3, 3, -4, 4, 5, 6, 10] categoryIds_Count = len(categoryIds) i = 0 List_Count_equals_0 = 0 #如果获取12次广告,广告数都为零,则切换至下一个帐号 while result_Code != '31307' and List_Count_equals_0 < 12: categoryId = categoryIds[i] [result_Code, data_by_categoryId] = self.viewAll_SilverAdverts_by_categoryId(categoryId) total_data += data_by_categoryId if result_Code == 0: List_Count_equals_0 += 1 i += 1 if i >= categoryIds_Count: i -= categoryIds_Count return total_data def start(self): for account in self.accountList: user, userName, passWord, imei = account logger.info("User Iteration Started: %s", user) login_result_dict = self.login(userName, passWord, imei) if login_result_dict["IsSuccess"]: try: total_data_by_all_categoryIds = self.get_all_silvers() logger.debug("total_data_by_all_categoryIds: %s" % total_data_by_all_categoryIds) except Exception as e: logger.exception(e) finally: logger.info("User Iteration Ended: %s", user) else: logger.warning("Login failed, login user: %s, error description: %s", user, login_result_dict["Desc"]) logger.info("---------------------------------------------------\n") def run_forever(self): while True: self.start() time.sleep(4*3600) if __name__ == '__main__': account_file = os.path.join(project_root_path, 'Config', 'Accounts.dat') mz = MiaoZuan(account_file) mz.run_forever()
MiaoZuan
identifier_name
MiaoZuanScripts.py
#!/usr/bin/python #encoding=utf-8 import urllib, urllib2 import cookielib import re import time from random import random from json import dumps as json_dumps, loads as json_loads import sys reload(sys) sys.setdefaultencoding('utf-8') import os project_root_path = os.path.abspath(os.path.join(os.path.dirname(__file__))) sys.path.append(project_root_path) from logger.logger import logFactory logger = logFactory.getLogger(__name__) class MiaoZuan(object): """docstring for MiaoZuan""" def __init__(self, account_file): super(MiaoZuan, self).__init__() self.headers = headers = { 'User-Agent':'IOS_8.1_IPHONE5C', 'm-lng':'113.331639', 'm-ct':'2', 'm-lat':'23.158624', 'm-cw':'320', 'm-iv':'3.0.1', 'm-ch':'568', 'm-cv':'6.5.2', 'm-lt':'1', 'm-nw':'WIFI', #'Content-Type':'application/json;charset=utf-8' } self.accountList = self.get_account_List(account_file) def get_account_List(self, account_file): accountList = [] try: with open(account_file, 'r') as f: lines = f.readlines() for line in lines: user, userName, passWord, imei = line.strip('\n').split(',') accountList.append([user, userName, passWord, imei]) except Exception as e: logger.exception(e) finally: return accountList def login(self, userName, passWord, imei): postdata = urllib.urlencode({ 'UserName':userName, 'Password':passWord, 'Imei':imei }) req = urllib2.Request( url='http://service.inkey.com/api/Auth/Login', data=postdata,
cookie_support = urllib2.HTTPCookieProcessor(cookielib.CookieJar()) opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler) urllib2.install_opener(opener) try: content = urllib2.urlopen(req).read() resp_dict = json_loads(content) return resp_dict except Exception as e: logger.exception(e) return {"IsSuccess": False, "Desc": ""} def pull_SilverAdvert_List(self, categoryId): postdata = urllib.urlencode({ 'CategoryIds':categoryId }) req = urllib2.Request( url='http://service.inkey.com/api/SilverAdvert/Pull', data = postdata, headers = self.headers ) try: content = urllib2.urlopen(req).read() silverAdvert_pat = re.compile(r'"Id":(.*?),') silverAdvert_list = re.findall(silverAdvert_pat, content) logger.debug("categoryId = %s, pull_SilverAdvert_List = %s", categoryId, silverAdvert_list) except Exception as e: logger.exception(e) silverAdvert_list = [] return silverAdvert_list def viewOne_SilverAdvert_by_advertsID(self, advertsID): postdata = urllib.urlencode({ 'IsGame':"false", "Id":advertsID }) req = urllib2.Request( url='http://service.inkey.com/api/SilverAdvert/GeneratedIntegral', data = postdata, headers = self.headers ) try: content = urllib2.urlopen(req).read() logger.debug("view advert id = %s, Response from the server: %s", advertsID, content) resp_dict = json_loads(content) return resp_dict except Exception as e: logger.exception(e) return {"IsSuccess": False} def viewAll_SilverAdverts_by_categoryId(self, categoryId): silverAdsList = self.pull_SilverAdvert_List(categoryId) silverAdsList_Count = len(silverAdsList) total_data_by_categoryId = 0 result_Code = 0 result_Code_31303_count = 0 selectNum = 0 if silverAdsList_Count > 0: while True: advertsID = silverAdsList[selectNum] resp_dict = self.viewOne_SilverAdvert_by_advertsID(advertsID) selectNum += 1 if selectNum >= silverAdsList_Count: selectNum -= silverAdsList_Count if resp_dict["IsSuccess"]: total_data_by_categoryId += resp_dict["Data"] logger.debug("get %s more points", resp_dict["Data"]) elif resp_dict["Code"] == 31303: logger.debug("view advert id = %s, Response from the server: %s", advertsID, resp_dict["Desc"]) result_Code_31303_count += 1 continue elif resp_dict["Code"] == 31307 or result_Code_31303_count > silverAdsList_Count: logger.debug("Response from the server: %s", resp_dict["Desc"]) break time.sleep(12+3*random()) logger.info("categoryId = %s, total_data_by_categoryId = %s" % (categoryId, total_data_by_categoryId)) return [result_Code, total_data_by_categoryId] def get_all_silvers(self): total_data = 0 result_Code = 0 categoryIds = [-1, 1, -2, 2, -3, 3, -4, 4, 5, 6, 10] categoryIds_Count = len(categoryIds) i = 0 List_Count_equals_0 = 0 #如果获取12次广告,广告数都为零,则切换至下一个帐号 while result_Code != '31307' and List_Count_equals_0 < 12: categoryId = categoryIds[i] [result_Code, data_by_categoryId] = self.viewAll_SilverAdverts_by_categoryId(categoryId) total_data += data_by_categoryId if result_Code == 0: List_Count_equals_0 += 1 i += 1 if i >= categoryIds_Count: i -= categoryIds_Count return total_data def start(self): for account in self.accountList: user, userName, passWord, imei = account logger.info("User Iteration Started: %s", user) login_result_dict = self.login(userName, passWord, imei) if login_result_dict["IsSuccess"]: try: total_data_by_all_categoryIds = self.get_all_silvers() logger.debug("total_data_by_all_categoryIds: %s" % total_data_by_all_categoryIds) except Exception as e: logger.exception(e) finally: logger.info("User Iteration Ended: %s", user) else: logger.warning("Login failed, login user: %s, error description: %s", user, login_result_dict["Desc"]) logger.info("---------------------------------------------------\n") def run_forever(self): while True: self.start() time.sleep(4*3600) if __name__ == '__main__': account_file = os.path.join(project_root_path, 'Config', 'Accounts.dat') mz = MiaoZuan(account_file) mz.run_forever()
headers=self.headers )
random_line_split
MiaoZuanScripts.py
#!/usr/bin/python #encoding=utf-8 import urllib, urllib2 import cookielib import re import time from random import random from json import dumps as json_dumps, loads as json_loads import sys reload(sys) sys.setdefaultencoding('utf-8') import os project_root_path = os.path.abspath(os.path.join(os.path.dirname(__file__))) sys.path.append(project_root_path) from logger.logger import logFactory logger = logFactory.getLogger(__name__) class MiaoZuan(object): """docstring for MiaoZuan""" def __init__(self, account_file): super(MiaoZuan, self).__init__() self.headers = headers = { 'User-Agent':'IOS_8.1_IPHONE5C', 'm-lng':'113.331639', 'm-ct':'2', 'm-lat':'23.158624', 'm-cw':'320', 'm-iv':'3.0.1', 'm-ch':'568', 'm-cv':'6.5.2', 'm-lt':'1', 'm-nw':'WIFI', #'Content-Type':'application/json;charset=utf-8' } self.accountList = self.get_account_List(account_file) def get_account_List(self, account_file): accountList = [] try: with open(account_file, 'r') as f: lines = f.readlines() for line in lines: user, userName, passWord, imei = line.strip('\n').split(',') accountList.append([user, userName, passWord, imei]) except Exception as e: logger.exception(e) finally: return accountList def login(self, userName, passWord, imei): postdata = urllib.urlencode({ 'UserName':userName, 'Password':passWord, 'Imei':imei }) req = urllib2.Request( url='http://service.inkey.com/api/Auth/Login', data=postdata, headers=self.headers ) cookie_support = urllib2.HTTPCookieProcessor(cookielib.CookieJar()) opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler) urllib2.install_opener(opener) try: content = urllib2.urlopen(req).read() resp_dict = json_loads(content) return resp_dict except Exception as e: logger.exception(e) return {"IsSuccess": False, "Desc": ""} def pull_SilverAdvert_List(self, categoryId): postdata = urllib.urlencode({ 'CategoryIds':categoryId }) req = urllib2.Request( url='http://service.inkey.com/api/SilverAdvert/Pull', data = postdata, headers = self.headers ) try: content = urllib2.urlopen(req).read() silverAdvert_pat = re.compile(r'"Id":(.*?),') silverAdvert_list = re.findall(silverAdvert_pat, content) logger.debug("categoryId = %s, pull_SilverAdvert_List = %s", categoryId, silverAdvert_list) except Exception as e: logger.exception(e) silverAdvert_list = [] return silverAdvert_list def viewOne_SilverAdvert_by_advertsID(self, advertsID): postdata = urllib.urlencode({ 'IsGame':"false", "Id":advertsID }) req = urllib2.Request( url='http://service.inkey.com/api/SilverAdvert/GeneratedIntegral', data = postdata, headers = self.headers ) try: content = urllib2.urlopen(req).read() logger.debug("view advert id = %s, Response from the server: %s", advertsID, content) resp_dict = json_loads(content) return resp_dict except Exception as e: logger.exception(e) return {"IsSuccess": False} def viewAll_SilverAdverts_by_categoryId(self, categoryId): silverAdsList = self.pull_SilverAdvert_List(categoryId) silverAdsList_Count = len(silverAdsList) total_data_by_categoryId = 0 result_Code = 0 result_Code_31303_count = 0 selectNum = 0 if silverAdsList_Count > 0: while True: advertsID = silverAdsList[selectNum] resp_dict = self.viewOne_SilverAdvert_by_advertsID(advertsID) selectNum += 1 if selectNum >= silverAdsList_Count:
if resp_dict["IsSuccess"]: total_data_by_categoryId += resp_dict["Data"] logger.debug("get %s more points", resp_dict["Data"]) elif resp_dict["Code"] == 31303: logger.debug("view advert id = %s, Response from the server: %s", advertsID, resp_dict["Desc"]) result_Code_31303_count += 1 continue elif resp_dict["Code"] == 31307 or result_Code_31303_count > silverAdsList_Count: logger.debug("Response from the server: %s", resp_dict["Desc"]) break time.sleep(12+3*random()) logger.info("categoryId = %s, total_data_by_categoryId = %s" % (categoryId, total_data_by_categoryId)) return [result_Code, total_data_by_categoryId] def get_all_silvers(self): total_data = 0 result_Code = 0 categoryIds = [-1, 1, -2, 2, -3, 3, -4, 4, 5, 6, 10] categoryIds_Count = len(categoryIds) i = 0 List_Count_equals_0 = 0 #如果获取12次广告,广告数都为零,则切换至下一个帐号 while result_Code != '31307' and List_Count_equals_0 < 12: categoryId = categoryIds[i] [result_Code, data_by_categoryId] = self.viewAll_SilverAdverts_by_categoryId(categoryId) total_data += data_by_categoryId if result_Code == 0: List_Count_equals_0 += 1 i += 1 if i >= categoryIds_Count: i -= categoryIds_Count return total_data def start(self): for account in self.accountList: user, userName, passWord, imei = account logger.info("User Iteration Started: %s", user) login_result_dict = self.login(userName, passWord, imei) if login_result_dict["IsSuccess"]: try: total_data_by_all_categoryIds = self.get_all_silvers() logger.debug("total_data_by_all_categoryIds: %s" % total_data_by_all_categoryIds) except Exception as e: logger.exception(e) finally: logger.info("User Iteration Ended: %s", user) else: logger.warning("Login failed, login user: %s, error description: %s", user, login_result_dict["Desc"]) logger.info("---------------------------------------------------\n") def run_forever(self): while True: self.start() time.sleep(4*3600) if __name__ == '__main__': account_file = os.path.join(project_root_path, 'Config', 'Accounts.dat') mz = MiaoZuan(account_file) mz.run_forever()
selectNum -= silverAdsList_Count
conditional_block
MiaoZuanScripts.py
#!/usr/bin/python #encoding=utf-8 import urllib, urllib2 import cookielib import re import time from random import random from json import dumps as json_dumps, loads as json_loads import sys reload(sys) sys.setdefaultencoding('utf-8') import os project_root_path = os.path.abspath(os.path.join(os.path.dirname(__file__))) sys.path.append(project_root_path) from logger.logger import logFactory logger = logFactory.getLogger(__name__) class MiaoZuan(object): """docstring for MiaoZuan""" def __init__(self, account_file): super(MiaoZuan, self).__init__() self.headers = headers = { 'User-Agent':'IOS_8.1_IPHONE5C', 'm-lng':'113.331639', 'm-ct':'2', 'm-lat':'23.158624', 'm-cw':'320', 'm-iv':'3.0.1', 'm-ch':'568', 'm-cv':'6.5.2', 'm-lt':'1', 'm-nw':'WIFI', #'Content-Type':'application/json;charset=utf-8' } self.accountList = self.get_account_List(account_file) def get_account_List(self, account_file): accountList = [] try: with open(account_file, 'r') as f: lines = f.readlines() for line in lines: user, userName, passWord, imei = line.strip('\n').split(',') accountList.append([user, userName, passWord, imei]) except Exception as e: logger.exception(e) finally: return accountList def login(self, userName, passWord, imei):
def pull_SilverAdvert_List(self, categoryId): postdata = urllib.urlencode({ 'CategoryIds':categoryId }) req = urllib2.Request( url='http://service.inkey.com/api/SilverAdvert/Pull', data = postdata, headers = self.headers ) try: content = urllib2.urlopen(req).read() silverAdvert_pat = re.compile(r'"Id":(.*?),') silverAdvert_list = re.findall(silverAdvert_pat, content) logger.debug("categoryId = %s, pull_SilverAdvert_List = %s", categoryId, silverAdvert_list) except Exception as e: logger.exception(e) silverAdvert_list = [] return silverAdvert_list def viewOne_SilverAdvert_by_advertsID(self, advertsID): postdata = urllib.urlencode({ 'IsGame':"false", "Id":advertsID }) req = urllib2.Request( url='http://service.inkey.com/api/SilverAdvert/GeneratedIntegral', data = postdata, headers = self.headers ) try: content = urllib2.urlopen(req).read() logger.debug("view advert id = %s, Response from the server: %s", advertsID, content) resp_dict = json_loads(content) return resp_dict except Exception as e: logger.exception(e) return {"IsSuccess": False} def viewAll_SilverAdverts_by_categoryId(self, categoryId): silverAdsList = self.pull_SilverAdvert_List(categoryId) silverAdsList_Count = len(silverAdsList) total_data_by_categoryId = 0 result_Code = 0 result_Code_31303_count = 0 selectNum = 0 if silverAdsList_Count > 0: while True: advertsID = silverAdsList[selectNum] resp_dict = self.viewOne_SilverAdvert_by_advertsID(advertsID) selectNum += 1 if selectNum >= silverAdsList_Count: selectNum -= silverAdsList_Count if resp_dict["IsSuccess"]: total_data_by_categoryId += resp_dict["Data"] logger.debug("get %s more points", resp_dict["Data"]) elif resp_dict["Code"] == 31303: logger.debug("view advert id = %s, Response from the server: %s", advertsID, resp_dict["Desc"]) result_Code_31303_count += 1 continue elif resp_dict["Code"] == 31307 or result_Code_31303_count > silverAdsList_Count: logger.debug("Response from the server: %s", resp_dict["Desc"]) break time.sleep(12+3*random()) logger.info("categoryId = %s, total_data_by_categoryId = %s" % (categoryId, total_data_by_categoryId)) return [result_Code, total_data_by_categoryId] def get_all_silvers(self): total_data = 0 result_Code = 0 categoryIds = [-1, 1, -2, 2, -3, 3, -4, 4, 5, 6, 10] categoryIds_Count = len(categoryIds) i = 0 List_Count_equals_0 = 0 #如果获取12次广告,广告数都为零,则切换至下一个帐号 while result_Code != '31307' and List_Count_equals_0 < 12: categoryId = categoryIds[i] [result_Code, data_by_categoryId] = self.viewAll_SilverAdverts_by_categoryId(categoryId) total_data += data_by_categoryId if result_Code == 0: List_Count_equals_0 += 1 i += 1 if i >= categoryIds_Count: i -= categoryIds_Count return total_data def start(self): for account in self.accountList: user, userName, passWord, imei = account logger.info("User Iteration Started: %s", user) login_result_dict = self.login(userName, passWord, imei) if login_result_dict["IsSuccess"]: try: total_data_by_all_categoryIds = self.get_all_silvers() logger.debug("total_data_by_all_categoryIds: %s" % total_data_by_all_categoryIds) except Exception as e: logger.exception(e) finally: logger.info("User Iteration Ended: %s", user) else: logger.warning("Login failed, login user: %s, error description: %s", user, login_result_dict["Desc"]) logger.info("---------------------------------------------------\n") def run_forever(self): while True: self.start() time.sleep(4*3600) if __name__ == '__main__': account_file = os.path.join(project_root_path, 'Config', 'Accounts.dat') mz = MiaoZuan(account_file) mz.run_forever()
postdata = urllib.urlencode({ 'UserName':userName, 'Password':passWord, 'Imei':imei }) req = urllib2.Request( url='http://service.inkey.com/api/Auth/Login', data=postdata, headers=self.headers ) cookie_support = urllib2.HTTPCookieProcessor(cookielib.CookieJar()) opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler) urllib2.install_opener(opener) try: content = urllib2.urlopen(req).read() resp_dict = json_loads(content) return resp_dict except Exception as e: logger.exception(e) return {"IsSuccess": False, "Desc": ""}
identifier_body
async_cmd_desc_map.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use crate::virtio::queue::DescriptorChain; use crate::virtio::video::command::QueueType; use crate::virtio::video::device::{AsyncCmdResponse, AsyncCmdTag}; use crate::virtio::video::error::VideoError; use crate::virtio::video::protocol; use crate::virtio::video::response::CmdResponse; /// AsyncCmdDescMap is a BTreeMap which stores descriptor chains in which asynchronous /// responses will be written. #[derive(Default)] pub struct AsyncCmdDescMap(BTreeMap<AsyncCmdTag, DescriptorChain>); impl AsyncCmdDescMap { pub fn insert(&mut self, tag: AsyncCmdTag, descriptor_chain: DescriptorChain) { self.0.insert(tag, descriptor_chain); } pub fn remove(&mut self, tag: &AsyncCmdTag) -> Option<DescriptorChain> { self.0.remove(tag) } /// Returns a list of `AsyncCmdResponse`s to cancel pending commands that target /// stream `target_stream_id`. /// If `target_queue_type` is specified, then only create the requests for the specified queue. /// Otherwise, create the requests for both input and output queue. /// If `processing_tag` is specified, a cancellation request for that tag will /// not be created. pub fn create_cancellation_responses( &self, target_stream_id: &u32, target_queue_type: Option<QueueType>, processing_tag: Option<AsyncCmdTag>, ) -> Vec<AsyncCmdResponse> { let mut responses = vec![]; for tag in self.0.keys().filter(|&&k| Some(k) != processing_tag) { match tag { AsyncCmdTag::Queue { stream_id, queue_type, .. } if stream_id == target_stream_id && target_queue_type.as_ref().unwrap_or(queue_type) == queue_type => { responses.push(AsyncCmdResponse::from_response( *tag, CmdResponse::ResourceQueue { timestamp: 0, flags: protocol::VIRTIO_VIDEO_BUFFER_FLAG_ERR, size: 0, }, )); } AsyncCmdTag::Drain { stream_id } if stream_id == target_stream_id => { // TODO(b/1518105): Use more appropriate error code if a new protocol supports // one. responses.push(AsyncCmdResponse::from_error( *tag, VideoError::InvalidOperation, )); } AsyncCmdTag::Clear { stream_id, queue_type, } if stream_id == target_stream_id && target_queue_type.as_ref().unwrap_or(queue_type) == queue_type =>
_ => { // Keep commands for other streams. } } } responses } }
{ // TODO(b/1518105): Use more appropriate error code if a new protocol supports // one. responses.push(AsyncCmdResponse::from_error( *tag, VideoError::InvalidOperation, )); }
conditional_block
async_cmd_desc_map.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use crate::virtio::queue::DescriptorChain; use crate::virtio::video::command::QueueType; use crate::virtio::video::device::{AsyncCmdResponse, AsyncCmdTag}; use crate::virtio::video::error::VideoError; use crate::virtio::video::protocol; use crate::virtio::video::response::CmdResponse; /// AsyncCmdDescMap is a BTreeMap which stores descriptor chains in which asynchronous /// responses will be written. #[derive(Default)] pub struct AsyncCmdDescMap(BTreeMap<AsyncCmdTag, DescriptorChain>);
impl AsyncCmdDescMap { pub fn insert(&mut self, tag: AsyncCmdTag, descriptor_chain: DescriptorChain) { self.0.insert(tag, descriptor_chain); } pub fn remove(&mut self, tag: &AsyncCmdTag) -> Option<DescriptorChain> { self.0.remove(tag) } /// Returns a list of `AsyncCmdResponse`s to cancel pending commands that target /// stream `target_stream_id`. /// If `target_queue_type` is specified, then only create the requests for the specified queue. /// Otherwise, create the requests for both input and output queue. /// If `processing_tag` is specified, a cancellation request for that tag will /// not be created. pub fn create_cancellation_responses( &self, target_stream_id: &u32, target_queue_type: Option<QueueType>, processing_tag: Option<AsyncCmdTag>, ) -> Vec<AsyncCmdResponse> { let mut responses = vec![]; for tag in self.0.keys().filter(|&&k| Some(k) != processing_tag) { match tag { AsyncCmdTag::Queue { stream_id, queue_type, .. } if stream_id == target_stream_id && target_queue_type.as_ref().unwrap_or(queue_type) == queue_type => { responses.push(AsyncCmdResponse::from_response( *tag, CmdResponse::ResourceQueue { timestamp: 0, flags: protocol::VIRTIO_VIDEO_BUFFER_FLAG_ERR, size: 0, }, )); } AsyncCmdTag::Drain { stream_id } if stream_id == target_stream_id => { // TODO(b/1518105): Use more appropriate error code if a new protocol supports // one. responses.push(AsyncCmdResponse::from_error( *tag, VideoError::InvalidOperation, )); } AsyncCmdTag::Clear { stream_id, queue_type, } if stream_id == target_stream_id && target_queue_type.as_ref().unwrap_or(queue_type) == queue_type => { // TODO(b/1518105): Use more appropriate error code if a new protocol supports // one. responses.push(AsyncCmdResponse::from_error( *tag, VideoError::InvalidOperation, )); } _ => { // Keep commands for other streams. } } } responses } }
random_line_split
async_cmd_desc_map.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use crate::virtio::queue::DescriptorChain; use crate::virtio::video::command::QueueType; use crate::virtio::video::device::{AsyncCmdResponse, AsyncCmdTag}; use crate::virtio::video::error::VideoError; use crate::virtio::video::protocol; use crate::virtio::video::response::CmdResponse; /// AsyncCmdDescMap is a BTreeMap which stores descriptor chains in which asynchronous /// responses will be written. #[derive(Default)] pub struct AsyncCmdDescMap(BTreeMap<AsyncCmdTag, DescriptorChain>); impl AsyncCmdDescMap { pub fn insert(&mut self, tag: AsyncCmdTag, descriptor_chain: DescriptorChain) { self.0.insert(tag, descriptor_chain); } pub fn remove(&mut self, tag: &AsyncCmdTag) -> Option<DescriptorChain> { self.0.remove(tag) } /// Returns a list of `AsyncCmdResponse`s to cancel pending commands that target /// stream `target_stream_id`. /// If `target_queue_type` is specified, then only create the requests for the specified queue. /// Otherwise, create the requests for both input and output queue. /// If `processing_tag` is specified, a cancellation request for that tag will /// not be created. pub fn create_cancellation_responses( &self, target_stream_id: &u32, target_queue_type: Option<QueueType>, processing_tag: Option<AsyncCmdTag>, ) -> Vec<AsyncCmdResponse>
}
{ let mut responses = vec![]; for tag in self.0.keys().filter(|&&k| Some(k) != processing_tag) { match tag { AsyncCmdTag::Queue { stream_id, queue_type, .. } if stream_id == target_stream_id && target_queue_type.as_ref().unwrap_or(queue_type) == queue_type => { responses.push(AsyncCmdResponse::from_response( *tag, CmdResponse::ResourceQueue { timestamp: 0, flags: protocol::VIRTIO_VIDEO_BUFFER_FLAG_ERR, size: 0, }, )); } AsyncCmdTag::Drain { stream_id } if stream_id == target_stream_id => { // TODO(b/1518105): Use more appropriate error code if a new protocol supports // one. responses.push(AsyncCmdResponse::from_error( *tag, VideoError::InvalidOperation, )); } AsyncCmdTag::Clear { stream_id, queue_type, } if stream_id == target_stream_id && target_queue_type.as_ref().unwrap_or(queue_type) == queue_type => { // TODO(b/1518105): Use more appropriate error code if a new protocol supports // one. responses.push(AsyncCmdResponse::from_error( *tag, VideoError::InvalidOperation, )); } _ => { // Keep commands for other streams. } } } responses }
identifier_body
async_cmd_desc_map.rs
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use crate::virtio::queue::DescriptorChain; use crate::virtio::video::command::QueueType; use crate::virtio::video::device::{AsyncCmdResponse, AsyncCmdTag}; use crate::virtio::video::error::VideoError; use crate::virtio::video::protocol; use crate::virtio::video::response::CmdResponse; /// AsyncCmdDescMap is a BTreeMap which stores descriptor chains in which asynchronous /// responses will be written. #[derive(Default)] pub struct
(BTreeMap<AsyncCmdTag, DescriptorChain>); impl AsyncCmdDescMap { pub fn insert(&mut self, tag: AsyncCmdTag, descriptor_chain: DescriptorChain) { self.0.insert(tag, descriptor_chain); } pub fn remove(&mut self, tag: &AsyncCmdTag) -> Option<DescriptorChain> { self.0.remove(tag) } /// Returns a list of `AsyncCmdResponse`s to cancel pending commands that target /// stream `target_stream_id`. /// If `target_queue_type` is specified, then only create the requests for the specified queue. /// Otherwise, create the requests for both input and output queue. /// If `processing_tag` is specified, a cancellation request for that tag will /// not be created. pub fn create_cancellation_responses( &self, target_stream_id: &u32, target_queue_type: Option<QueueType>, processing_tag: Option<AsyncCmdTag>, ) -> Vec<AsyncCmdResponse> { let mut responses = vec![]; for tag in self.0.keys().filter(|&&k| Some(k) != processing_tag) { match tag { AsyncCmdTag::Queue { stream_id, queue_type, .. } if stream_id == target_stream_id && target_queue_type.as_ref().unwrap_or(queue_type) == queue_type => { responses.push(AsyncCmdResponse::from_response( *tag, CmdResponse::ResourceQueue { timestamp: 0, flags: protocol::VIRTIO_VIDEO_BUFFER_FLAG_ERR, size: 0, }, )); } AsyncCmdTag::Drain { stream_id } if stream_id == target_stream_id => { // TODO(b/1518105): Use more appropriate error code if a new protocol supports // one. responses.push(AsyncCmdResponse::from_error( *tag, VideoError::InvalidOperation, )); } AsyncCmdTag::Clear { stream_id, queue_type, } if stream_id == target_stream_id && target_queue_type.as_ref().unwrap_or(queue_type) == queue_type => { // TODO(b/1518105): Use more appropriate error code if a new protocol supports // one. responses.push(AsyncCmdResponse::from_error( *tag, VideoError::InvalidOperation, )); } _ => { // Keep commands for other streams. } } } responses } }
AsyncCmdDescMap
identifier_name
zephyr.py
#!/usr/bin/env python3 # # Copyright (c) 2015, Roberto Riggio # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the CREATE-NET nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY CREATE-NET ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL CREATE-NET BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Basic Zephyr manager.""" from empower.core.app import EmpowerApp from empower.core.app import DEFAULT_PERIOD from empower.main import RUNTIME from empower.datatypes.etheraddress import EtherAddress from empower.core.resourcepool import ResourcePool from empower.lvapp.lvappconnection import LVAPPConnection import time, datetime, threading import empower.apps.zephyr.zephyrLinker as linker starttime = datetime.datetime.now() class Zephyr(EmpowerApp): """Basic mobility manager. Command Line Parameters: tenant_id: tenant id limit: handover limit in dBm (optional, default -80) every: loop period in ms (optional, default 5000ms) Example: ./empower-runtime.py apps.mobilitymanager.mobilitymanager \ --tenant_id=52313ecb-9d00-4b7d-b873-b55d3d9ada26 """ def __init__(self, **kwargs): self.__limit = linker.DEFAULT_RSSI_LIMIT EmpowerApp.__init__(self, **kwargs) # Register an wtp up event self.wtpup(callback=self.wtp_up_callback) # Register an lvap join event self.lvapjoin(callback=self.lvap_join_callback) # Register an lvap leave event self.lvapleave(callback=self.lvap_leave_callback) def lvap_leave_callback(self, lvap): """Called when an LVAP disassociates from a tennant.""" self.log.info("LVAP %s left %s" % (lvap.addr, lvap.ssid)) def wtp_up_callback(self, wtp): """Called when a new WTP connects to the controller.""" for block in wtp.supports: self.ucqm(block=block, every=self.every) def lvap_join_callback(self, lvap): """Called when an joins the network.""" self.rssi(lvap=lvap.addr, value=self.limit, relation='LT', callback=self.low_rssi) def handover(self, lvap): """ Handover the LVAP to a WTP with an RSSI higher that -65dB. """ self.log.info("Running handover...") self.log.info("LVAP: %s - Limit RSSI : %u dB" % (lvap.addr, self.limit)) self.log.info("Initialize the Resource Pool") pool = ResourcePool() for wtp in self.wtps(): #for wtpd, lvaps in wtpdict.items(): #self.log.info("WTP in wtps : %s WTP in dict : %s are equal : %u\n" % (str(wtp.addr), wtpd, (wtp.addr == wtpd))) templist = linker.wtpdict[str(wtp.addr)] length = len(templist) self.log.info("Pooling WTP: %s" % str(wtp.addr)) self.log.info(wtp.supports) pool = pool | wtp.supports self.log.info("Select matching Resource Blocks") matches = pool #& lvap.scheduled_on self.log.info(matches) self.log.info("LVAP1 LOOP 107") counter=0 for lvap in self.lvaps(): self.log.info("!!!!!!!!!!!!!!!%d : %s" % (counter, lvap.addr)) counter=counter+1 for block in matches: self.log.info("Time : %f \n LVAP : %s \n addr : %s \n last_rssi_avg : %.2f \n last_rssi_std : %.2f \n last_packets : %u \n mov_rrsi : %.2f\n" % (time.time(), lvap.addr, block.ucqm[lvap.addr]['addr'], block.ucqm[lvap.addr]['last_rssi_avg'], block.ucqm[lvap.addr]['last_rssi_std'], block.ucqm[lvap.addr]['last_packets'], block.ucqm[lvap.addr]['mov_rssi'])) if (lvap.addr=="78:44:76:BF:DA:D4"): self.log.info("LVAP: %s is leaving" % lvap.addr) #del lvap.downlink[block] #deletes lvap # Initialize the Resource Pool pool = ResourcePool() # Update the Resource Pool with all # the available Resourse Blocks for wtp in self.wtps(): if (str(wtp.addr) in linker.wtpdict): if (len(linker.wtpdict[str(wtp.addr)]) < linker.wtpdict_limit[str(wtp.addr)]): pool = pool | wtp.supports # Select matching Resource Blocks matches = pool & lvap.scheduled_on # Filter Resource Blocks by RSSI valid = [block for block in matches if block.ucqm[lvap.addr]['mov_rssi'] >= self.limit] #valid = self.blocks(lvap, self.limit) if not valid: self.log.info("not valid") return for block in valid: self.log.info("valid LVAP: %s - Current RSSI : %u dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) new_block = max(valid, key=lambda x: x.ucqm[lvap.addr]['mov_rssi']) self.log.info("LVAP %s setting new block %s" % (lvap.addr, new_block)) lvap.scheduled_on = new_block @property def limit(self): """Return loop period.""" return self.__limit @limit.setter def limit(self, value): """Set limit.""" limit = int(value) if limit > 0 or limit < -100: raise ValueError("Invalid value for limit") self.log.info("Setting limit %u dB" % value) self.__limit = limit def set_limit(self, value): """Set limit.""" limit = int(value) if limit > 0 or limit < -100: raise ValueError("Invalid value for limit") self.log.info("Setting limit %u dB" % value) self.__limit = limit def low_rssi(self, trigger): """ Perform handover if an LVAP's rssi is going below the threshold. """ self.log.info("Received trigger from %s rssi %u dB", trigger.event['block'], trigger.event['current']) lvap = self.lvap(trigger.lvap) if not lvap: return self.handover(lvap) def wtp_clientlimit(self): self.log.info("Running Client Limit...") wtp_c=0 for wtp in self.wtps(): #Create lvaplist for the specific wtp lvaplist = [] for lvap in self.lvaps(): if lvap.wtp.addr == wtp.addr: #self.log.info("LVAP before list : %s" % lvap.addr) lvaplist.append(str(lvap.addr)) #self.log.info("LVAP after list : %s" % lvaplist[-1]) #Check if limit is not given and provide the default #if str(wtp.addr) not in linker.wtpdict_limit: #linker.wtpdict_limit[str(wtp.addr)]=linker.DEFAULT_LVAP_NUMBER_LIMIT #Check if wtp is not on the list and add it if str(wtp.addr) not in linker.wtpdict: linker.wtpdict[str(wtp.addr)] = lvaplist #If limit is -1 then wtp has no limit if linker.wtpdict_limit[str(wtp.addr)] == -1: self.log.info("################ WTP : %s has unlimited LVAPs (limit %f) %s ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)], linker.wtpdict[str(wtp.addr)])) continue #If wtp client limit is exceeded, then handover the excess lvaps to new wtp elif len(lvaplist) > linker.wtpdict_limit[str(wtp.addr)]: self.log.info("################ WTP : %s has more LVAPs than the limit %f ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)])) self.log.info(lvaplist) self.log.info(linker.wtpdict[str(wtp.addr)]) diff = [a for a in lvaplist+linker.wtpdict[str(wtp.addr)] if (a not in lvaplist) or (a not in linker.wtpdict[str(wtp.addr)])] self.log.info(diff) numoflvaptohandover=len(lvaplist) - linker.wtpdict_limit[str(wtp.addr)] self.log.info(numoflvaptohandover) for lvap in self.lvaps(): #If lvap is the extra lvap in wtp then find wtp with best rssi and handover to that if lvap.addr in diff or lvap.addr in lvaplist: self.log.info("If lvap in diff") # Initialize the Resource Pool pool = ResourcePool() # Update the Resource Pool with all # the available Resourse Blocks for other_wtp in self.wtps(): if other_wtp.addr != wtp.addr: if linker.wtpdict_limit[str(other_wtp.addr)] < len(linker.wtpdict[str(other_wtp.addr)]): self.log.info(linker.wtpdict_limit[str(other_wtp.addr)]) self.log.info(len(linker.wtpdict[str(other_wtp.addr)])) pool = pool | other_wtp.supports # Select matching Resource Blocks matches = pool & lvap.scheduled_on max_rssi = -float("inf") first_block=1; for block in matches: if first_block == 1: first_block=0 max_rssi=block.ucqm[lvap.addr]['mov_rssi'] else: if max_rssi < block.ucqm[lvap.addr]['mov_rssi']:
# Filter Resource Blocks by RSSI valid = [block for block in matches if block.ucqm[lvap.addr]['mov_rssi'] >= max_rssi] if not valid: self.log.info("not valid") continue for block in valid: self.log.info("valid LVAP: %s - Current RSSI : %.2f dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) #Remove from lvaplist lvaplist.remove(str(lvap.addr)) new_block = max(valid, key=lambda x: x.ucqm[lvap.addr]['mov_rssi']) self.log.info("LVAP %s setting new block %s" % (lvap.addr, new_block)) lvap.scheduled_on = new_block numoflvaptohandover=numoflvaptohandover-1 else: continue #if all lvaps have been handovered then break if numoflvaptohandover == 0: break else: self.log.info("################ WTP : %s has LVAPs' limit %f %s ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)], linker.wtpdict[str(wtp.addr)])) #Update lvaplist for given wtp linker.wtpdict[str(wtp.addr)] = lvaplist for wtp, lvaps in linker.wtpdict.items(): temp = None insert_comma = 0 for lvap in lvaps: if insert_comma == 0: temp = lvap insert_comma=1 continue temp = temp + ', ' + lvap #str(lvaps).strip('['']')#.strip('[EtherAddress'']') self.log.info("WTP : %s has %u LVAPs : %s\n" % (wtp, len(lvaps), temp)) #self.wtp_lvap_limit(wtp,lvaps) #if len(lvaps) > linker.DEFAULT_LVAP_NUMBER_LIMIT: #self.log.info("################WTP : %s has more LVAPs than the limit######################\n" % wtp) #for wtp in self.wtps() def lvap_timelimit(self): self.log.info("Running Time Limit...") self.log.info("DEFAULT_LVAP_TIME_LIMIT : %d" % linker.DEFAULT_LVAP_TIME_LIMIT) deletionlist = [] for lvap, endtime in linker.lvap_timer.items(): #self.log.info("LVAP") formated_endtime = datetime.datetime.strptime(endtime, '%Y-%m-%d %H:%M:%S') currenttime = datetime.datetime.now() if (currenttime - formated_endtime).total_seconds() >= 0: self.log.info("$$$$$$$$$$$$$ LVAP: %s Time ends" % lvap) deletionlist.append(lvap) else: self.log.info("$$$$$$$$$$$$$ LVAP: %s Time continues" % lvap) for dlvap in deletionlist: self.log.info("$$$$$$$$$$$$$ Removing Timer LVAP: %s" % dlvap) linker.removeLVAPTimer(self,dlvap) for lvap in self.lvaps(): if str(lvap.addr) == dlvap: lvaplabel=RUNTIME.get_label(lvap.addr) self.log.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$") #del lvap.downlink[lvap.block] #deletes lvap #del RUNTIME.lvaps[lvap.addr] for wtp in self.wtps(): if lvap.wtp.addr == wtp.addr: #wtp.connection.send_del_lvap(lvap) RUNTIME.remove_lvap(lvap.addr) temp = linker.wtpdict[str(wtp.addr)] temp.remove(str(lvap.addr)) #del RUNTIME.lvaps[lvap.addr] break #self.remove_lvap(lvap) lvaplabel=RUNTIME.get_label(lvap.addr) #self.log.info(lvaplabel) self.log.info("Deleting LVAP %s from db" % lvaplabel) self.log.info("Removing %s %s from allowed LVAPs" % (lvaplabel, lvap.addr)) RUNTIME.remove_allowed(lvap.addr) self.log.info("Adding %s %s to denied LVAPs" % (lvaplabel, lvap.addr)) RUNTIME.add_denied(lvap.addr,lvaplabel) self.log.info("LVAP %s deleted" % lvaplabel) break #pool = ResourcePool() #for lvap in self.lvaps(): # matches = pool # for block in matches: # self.log.info("zephyr : LVAP: %s - Current RSSI : %f dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) def loop(self): """ Periodic job. """ self.log.info("Periodic job.\n") self.log.info("Allowed LVAPs: %s" % (RUNTIME.allowed)) self.log.info("Denied LVAPs: %s\n" % (RUNTIME.denied)) if linker.initialize_limit == 1: for wtp in self.wtps(): #Check if limit is not given and provide the default if str(wtp.addr) not in linker.wtpdict_limit: linker.wtpdict_limit[str(wtp.addr)]=linker.DEFAULT_LVAP_NUMBER_LIMIT linker.initialize_limit = 0 self.log.info("Setting limit to default") self.wtp_clientlimit() self.lvap_timelimit() self.log.info("Current limit %u linker limit to %u" % (self.limit,linker.RSSI_LIMIT)) if self.limit != linker.RSSI_LIMIT: self.log.info("Current limit %u setting limit to %u" % (self.limit,linker.RSSI_LIMIT)) self.set_limit(linker.RSSI_LIMIT) # Handover every active LVAP to # the best WTP counterlvap=0 for lvap in self.lvaps(): self.handover(lvap) counterlvap=counterlvap+1 self.log.info("Active LVAPs: %u" % counterlvap) def launch(tenant_id, limit=linker.DEFAULT_RSSI_LIMIT, every=DEFAULT_PERIOD): """ Initialize the module. """ return Zephyr(tenant_id=tenant_id, limit=limit, every=every)
max_rssi=block.ucqm[lvap.addr]['mov_rssi']
conditional_block
zephyr.py
#!/usr/bin/env python3 # # Copyright (c) 2015, Roberto Riggio # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the CREATE-NET nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY CREATE-NET ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL CREATE-NET BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Basic Zephyr manager.""" from empower.core.app import EmpowerApp from empower.core.app import DEFAULT_PERIOD from empower.main import RUNTIME from empower.datatypes.etheraddress import EtherAddress from empower.core.resourcepool import ResourcePool from empower.lvapp.lvappconnection import LVAPPConnection import time, datetime, threading import empower.apps.zephyr.zephyrLinker as linker starttime = datetime.datetime.now() class Zephyr(EmpowerApp): """Basic mobility manager. Command Line Parameters: tenant_id: tenant id limit: handover limit in dBm (optional, default -80) every: loop period in ms (optional, default 5000ms) Example: ./empower-runtime.py apps.mobilitymanager.mobilitymanager \ --tenant_id=52313ecb-9d00-4b7d-b873-b55d3d9ada26 """ def __init__(self, **kwargs): self.__limit = linker.DEFAULT_RSSI_LIMIT EmpowerApp.__init__(self, **kwargs) # Register an wtp up event self.wtpup(callback=self.wtp_up_callback) # Register an lvap join event self.lvapjoin(callback=self.lvap_join_callback) # Register an lvap leave event self.lvapleave(callback=self.lvap_leave_callback) def lvap_leave_callback(self, lvap): """Called when an LVAP disassociates from a tennant.""" self.log.info("LVAP %s left %s" % (lvap.addr, lvap.ssid)) def wtp_up_callback(self, wtp): """Called when a new WTP connects to the controller.""" for block in wtp.supports: self.ucqm(block=block, every=self.every) def
(self, lvap): """Called when an joins the network.""" self.rssi(lvap=lvap.addr, value=self.limit, relation='LT', callback=self.low_rssi) def handover(self, lvap): """ Handover the LVAP to a WTP with an RSSI higher that -65dB. """ self.log.info("Running handover...") self.log.info("LVAP: %s - Limit RSSI : %u dB" % (lvap.addr, self.limit)) self.log.info("Initialize the Resource Pool") pool = ResourcePool() for wtp in self.wtps(): #for wtpd, lvaps in wtpdict.items(): #self.log.info("WTP in wtps : %s WTP in dict : %s are equal : %u\n" % (str(wtp.addr), wtpd, (wtp.addr == wtpd))) templist = linker.wtpdict[str(wtp.addr)] length = len(templist) self.log.info("Pooling WTP: %s" % str(wtp.addr)) self.log.info(wtp.supports) pool = pool | wtp.supports self.log.info("Select matching Resource Blocks") matches = pool #& lvap.scheduled_on self.log.info(matches) self.log.info("LVAP1 LOOP 107") counter=0 for lvap in self.lvaps(): self.log.info("!!!!!!!!!!!!!!!%d : %s" % (counter, lvap.addr)) counter=counter+1 for block in matches: self.log.info("Time : %f \n LVAP : %s \n addr : %s \n last_rssi_avg : %.2f \n last_rssi_std : %.2f \n last_packets : %u \n mov_rrsi : %.2f\n" % (time.time(), lvap.addr, block.ucqm[lvap.addr]['addr'], block.ucqm[lvap.addr]['last_rssi_avg'], block.ucqm[lvap.addr]['last_rssi_std'], block.ucqm[lvap.addr]['last_packets'], block.ucqm[lvap.addr]['mov_rssi'])) if (lvap.addr=="78:44:76:BF:DA:D4"): self.log.info("LVAP: %s is leaving" % lvap.addr) #del lvap.downlink[block] #deletes lvap # Initialize the Resource Pool pool = ResourcePool() # Update the Resource Pool with all # the available Resourse Blocks for wtp in self.wtps(): if (str(wtp.addr) in linker.wtpdict): if (len(linker.wtpdict[str(wtp.addr)]) < linker.wtpdict_limit[str(wtp.addr)]): pool = pool | wtp.supports # Select matching Resource Blocks matches = pool & lvap.scheduled_on # Filter Resource Blocks by RSSI valid = [block for block in matches if block.ucqm[lvap.addr]['mov_rssi'] >= self.limit] #valid = self.blocks(lvap, self.limit) if not valid: self.log.info("not valid") return for block in valid: self.log.info("valid LVAP: %s - Current RSSI : %u dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) new_block = max(valid, key=lambda x: x.ucqm[lvap.addr]['mov_rssi']) self.log.info("LVAP %s setting new block %s" % (lvap.addr, new_block)) lvap.scheduled_on = new_block @property def limit(self): """Return loop period.""" return self.__limit @limit.setter def limit(self, value): """Set limit.""" limit = int(value) if limit > 0 or limit < -100: raise ValueError("Invalid value for limit") self.log.info("Setting limit %u dB" % value) self.__limit = limit def set_limit(self, value): """Set limit.""" limit = int(value) if limit > 0 or limit < -100: raise ValueError("Invalid value for limit") self.log.info("Setting limit %u dB" % value) self.__limit = limit def low_rssi(self, trigger): """ Perform handover if an LVAP's rssi is going below the threshold. """ self.log.info("Received trigger from %s rssi %u dB", trigger.event['block'], trigger.event['current']) lvap = self.lvap(trigger.lvap) if not lvap: return self.handover(lvap) def wtp_clientlimit(self): self.log.info("Running Client Limit...") wtp_c=0 for wtp in self.wtps(): #Create lvaplist for the specific wtp lvaplist = [] for lvap in self.lvaps(): if lvap.wtp.addr == wtp.addr: #self.log.info("LVAP before list : %s" % lvap.addr) lvaplist.append(str(lvap.addr)) #self.log.info("LVAP after list : %s" % lvaplist[-1]) #Check if limit is not given and provide the default #if str(wtp.addr) not in linker.wtpdict_limit: #linker.wtpdict_limit[str(wtp.addr)]=linker.DEFAULT_LVAP_NUMBER_LIMIT #Check if wtp is not on the list and add it if str(wtp.addr) not in linker.wtpdict: linker.wtpdict[str(wtp.addr)] = lvaplist #If limit is -1 then wtp has no limit if linker.wtpdict_limit[str(wtp.addr)] == -1: self.log.info("################ WTP : %s has unlimited LVAPs (limit %f) %s ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)], linker.wtpdict[str(wtp.addr)])) continue #If wtp client limit is exceeded, then handover the excess lvaps to new wtp elif len(lvaplist) > linker.wtpdict_limit[str(wtp.addr)]: self.log.info("################ WTP : %s has more LVAPs than the limit %f ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)])) self.log.info(lvaplist) self.log.info(linker.wtpdict[str(wtp.addr)]) diff = [a for a in lvaplist+linker.wtpdict[str(wtp.addr)] if (a not in lvaplist) or (a not in linker.wtpdict[str(wtp.addr)])] self.log.info(diff) numoflvaptohandover=len(lvaplist) - linker.wtpdict_limit[str(wtp.addr)] self.log.info(numoflvaptohandover) for lvap in self.lvaps(): #If lvap is the extra lvap in wtp then find wtp with best rssi and handover to that if lvap.addr in diff or lvap.addr in lvaplist: self.log.info("If lvap in diff") # Initialize the Resource Pool pool = ResourcePool() # Update the Resource Pool with all # the available Resourse Blocks for other_wtp in self.wtps(): if other_wtp.addr != wtp.addr: if linker.wtpdict_limit[str(other_wtp.addr)] < len(linker.wtpdict[str(other_wtp.addr)]): self.log.info(linker.wtpdict_limit[str(other_wtp.addr)]) self.log.info(len(linker.wtpdict[str(other_wtp.addr)])) pool = pool | other_wtp.supports # Select matching Resource Blocks matches = pool & lvap.scheduled_on max_rssi = -float("inf") first_block=1; for block in matches: if first_block == 1: first_block=0 max_rssi=block.ucqm[lvap.addr]['mov_rssi'] else: if max_rssi < block.ucqm[lvap.addr]['mov_rssi']: max_rssi=block.ucqm[lvap.addr]['mov_rssi'] # Filter Resource Blocks by RSSI valid = [block for block in matches if block.ucqm[lvap.addr]['mov_rssi'] >= max_rssi] if not valid: self.log.info("not valid") continue for block in valid: self.log.info("valid LVAP: %s - Current RSSI : %.2f dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) #Remove from lvaplist lvaplist.remove(str(lvap.addr)) new_block = max(valid, key=lambda x: x.ucqm[lvap.addr]['mov_rssi']) self.log.info("LVAP %s setting new block %s" % (lvap.addr, new_block)) lvap.scheduled_on = new_block numoflvaptohandover=numoflvaptohandover-1 else: continue #if all lvaps have been handovered then break if numoflvaptohandover == 0: break else: self.log.info("################ WTP : %s has LVAPs' limit %f %s ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)], linker.wtpdict[str(wtp.addr)])) #Update lvaplist for given wtp linker.wtpdict[str(wtp.addr)] = lvaplist for wtp, lvaps in linker.wtpdict.items(): temp = None insert_comma = 0 for lvap in lvaps: if insert_comma == 0: temp = lvap insert_comma=1 continue temp = temp + ', ' + lvap #str(lvaps).strip('['']')#.strip('[EtherAddress'']') self.log.info("WTP : %s has %u LVAPs : %s\n" % (wtp, len(lvaps), temp)) #self.wtp_lvap_limit(wtp,lvaps) #if len(lvaps) > linker.DEFAULT_LVAP_NUMBER_LIMIT: #self.log.info("################WTP : %s has more LVAPs than the limit######################\n" % wtp) #for wtp in self.wtps() def lvap_timelimit(self): self.log.info("Running Time Limit...") self.log.info("DEFAULT_LVAP_TIME_LIMIT : %d" % linker.DEFAULT_LVAP_TIME_LIMIT) deletionlist = [] for lvap, endtime in linker.lvap_timer.items(): #self.log.info("LVAP") formated_endtime = datetime.datetime.strptime(endtime, '%Y-%m-%d %H:%M:%S') currenttime = datetime.datetime.now() if (currenttime - formated_endtime).total_seconds() >= 0: self.log.info("$$$$$$$$$$$$$ LVAP: %s Time ends" % lvap) deletionlist.append(lvap) else: self.log.info("$$$$$$$$$$$$$ LVAP: %s Time continues" % lvap) for dlvap in deletionlist: self.log.info("$$$$$$$$$$$$$ Removing Timer LVAP: %s" % dlvap) linker.removeLVAPTimer(self,dlvap) for lvap in self.lvaps(): if str(lvap.addr) == dlvap: lvaplabel=RUNTIME.get_label(lvap.addr) self.log.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$") #del lvap.downlink[lvap.block] #deletes lvap #del RUNTIME.lvaps[lvap.addr] for wtp in self.wtps(): if lvap.wtp.addr == wtp.addr: #wtp.connection.send_del_lvap(lvap) RUNTIME.remove_lvap(lvap.addr) temp = linker.wtpdict[str(wtp.addr)] temp.remove(str(lvap.addr)) #del RUNTIME.lvaps[lvap.addr] break #self.remove_lvap(lvap) lvaplabel=RUNTIME.get_label(lvap.addr) #self.log.info(lvaplabel) self.log.info("Deleting LVAP %s from db" % lvaplabel) self.log.info("Removing %s %s from allowed LVAPs" % (lvaplabel, lvap.addr)) RUNTIME.remove_allowed(lvap.addr) self.log.info("Adding %s %s to denied LVAPs" % (lvaplabel, lvap.addr)) RUNTIME.add_denied(lvap.addr,lvaplabel) self.log.info("LVAP %s deleted" % lvaplabel) break #pool = ResourcePool() #for lvap in self.lvaps(): # matches = pool # for block in matches: # self.log.info("zephyr : LVAP: %s - Current RSSI : %f dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) def loop(self): """ Periodic job. """ self.log.info("Periodic job.\n") self.log.info("Allowed LVAPs: %s" % (RUNTIME.allowed)) self.log.info("Denied LVAPs: %s\n" % (RUNTIME.denied)) if linker.initialize_limit == 1: for wtp in self.wtps(): #Check if limit is not given and provide the default if str(wtp.addr) not in linker.wtpdict_limit: linker.wtpdict_limit[str(wtp.addr)]=linker.DEFAULT_LVAP_NUMBER_LIMIT linker.initialize_limit = 0 self.log.info("Setting limit to default") self.wtp_clientlimit() self.lvap_timelimit() self.log.info("Current limit %u linker limit to %u" % (self.limit,linker.RSSI_LIMIT)) if self.limit != linker.RSSI_LIMIT: self.log.info("Current limit %u setting limit to %u" % (self.limit,linker.RSSI_LIMIT)) self.set_limit(linker.RSSI_LIMIT) # Handover every active LVAP to # the best WTP counterlvap=0 for lvap in self.lvaps(): self.handover(lvap) counterlvap=counterlvap+1 self.log.info("Active LVAPs: %u" % counterlvap) def launch(tenant_id, limit=linker.DEFAULT_RSSI_LIMIT, every=DEFAULT_PERIOD): """ Initialize the module. """ return Zephyr(tenant_id=tenant_id, limit=limit, every=every)
lvap_join_callback
identifier_name
zephyr.py
#!/usr/bin/env python3 # # Copyright (c) 2015, Roberto Riggio # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the CREATE-NET nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY CREATE-NET ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL CREATE-NET BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Basic Zephyr manager.""" from empower.core.app import EmpowerApp from empower.core.app import DEFAULT_PERIOD from empower.main import RUNTIME from empower.datatypes.etheraddress import EtherAddress from empower.core.resourcepool import ResourcePool from empower.lvapp.lvappconnection import LVAPPConnection import time, datetime, threading import empower.apps.zephyr.zephyrLinker as linker starttime = datetime.datetime.now() class Zephyr(EmpowerApp): """Basic mobility manager. Command Line Parameters: tenant_id: tenant id limit: handover limit in dBm (optional, default -80) every: loop period in ms (optional, default 5000ms) Example: ./empower-runtime.py apps.mobilitymanager.mobilitymanager \ --tenant_id=52313ecb-9d00-4b7d-b873-b55d3d9ada26 """ def __init__(self, **kwargs): self.__limit = linker.DEFAULT_RSSI_LIMIT EmpowerApp.__init__(self, **kwargs) # Register an wtp up event self.wtpup(callback=self.wtp_up_callback) # Register an lvap join event self.lvapjoin(callback=self.lvap_join_callback) # Register an lvap leave event self.lvapleave(callback=self.lvap_leave_callback) def lvap_leave_callback(self, lvap): """Called when an LVAP disassociates from a tennant.""" self.log.info("LVAP %s left %s" % (lvap.addr, lvap.ssid)) def wtp_up_callback(self, wtp):
def lvap_join_callback(self, lvap): """Called when an joins the network.""" self.rssi(lvap=lvap.addr, value=self.limit, relation='LT', callback=self.low_rssi) def handover(self, lvap): """ Handover the LVAP to a WTP with an RSSI higher that -65dB. """ self.log.info("Running handover...") self.log.info("LVAP: %s - Limit RSSI : %u dB" % (lvap.addr, self.limit)) self.log.info("Initialize the Resource Pool") pool = ResourcePool() for wtp in self.wtps(): #for wtpd, lvaps in wtpdict.items(): #self.log.info("WTP in wtps : %s WTP in dict : %s are equal : %u\n" % (str(wtp.addr), wtpd, (wtp.addr == wtpd))) templist = linker.wtpdict[str(wtp.addr)] length = len(templist) self.log.info("Pooling WTP: %s" % str(wtp.addr)) self.log.info(wtp.supports) pool = pool | wtp.supports self.log.info("Select matching Resource Blocks") matches = pool #& lvap.scheduled_on self.log.info(matches) self.log.info("LVAP1 LOOP 107") counter=0 for lvap in self.lvaps(): self.log.info("!!!!!!!!!!!!!!!%d : %s" % (counter, lvap.addr)) counter=counter+1 for block in matches: self.log.info("Time : %f \n LVAP : %s \n addr : %s \n last_rssi_avg : %.2f \n last_rssi_std : %.2f \n last_packets : %u \n mov_rrsi : %.2f\n" % (time.time(), lvap.addr, block.ucqm[lvap.addr]['addr'], block.ucqm[lvap.addr]['last_rssi_avg'], block.ucqm[lvap.addr]['last_rssi_std'], block.ucqm[lvap.addr]['last_packets'], block.ucqm[lvap.addr]['mov_rssi'])) if (lvap.addr=="78:44:76:BF:DA:D4"): self.log.info("LVAP: %s is leaving" % lvap.addr) #del lvap.downlink[block] #deletes lvap # Initialize the Resource Pool pool = ResourcePool() # Update the Resource Pool with all # the available Resourse Blocks for wtp in self.wtps(): if (str(wtp.addr) in linker.wtpdict): if (len(linker.wtpdict[str(wtp.addr)]) < linker.wtpdict_limit[str(wtp.addr)]): pool = pool | wtp.supports # Select matching Resource Blocks matches = pool & lvap.scheduled_on # Filter Resource Blocks by RSSI valid = [block for block in matches if block.ucqm[lvap.addr]['mov_rssi'] >= self.limit] #valid = self.blocks(lvap, self.limit) if not valid: self.log.info("not valid") return for block in valid: self.log.info("valid LVAP: %s - Current RSSI : %u dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) new_block = max(valid, key=lambda x: x.ucqm[lvap.addr]['mov_rssi']) self.log.info("LVAP %s setting new block %s" % (lvap.addr, new_block)) lvap.scheduled_on = new_block @property def limit(self): """Return loop period.""" return self.__limit @limit.setter def limit(self, value): """Set limit.""" limit = int(value) if limit > 0 or limit < -100: raise ValueError("Invalid value for limit") self.log.info("Setting limit %u dB" % value) self.__limit = limit def set_limit(self, value): """Set limit.""" limit = int(value) if limit > 0 or limit < -100: raise ValueError("Invalid value for limit") self.log.info("Setting limit %u dB" % value) self.__limit = limit def low_rssi(self, trigger): """ Perform handover if an LVAP's rssi is going below the threshold. """ self.log.info("Received trigger from %s rssi %u dB", trigger.event['block'], trigger.event['current']) lvap = self.lvap(trigger.lvap) if not lvap: return self.handover(lvap) def wtp_clientlimit(self): self.log.info("Running Client Limit...") wtp_c=0 for wtp in self.wtps(): #Create lvaplist for the specific wtp lvaplist = [] for lvap in self.lvaps(): if lvap.wtp.addr == wtp.addr: #self.log.info("LVAP before list : %s" % lvap.addr) lvaplist.append(str(lvap.addr)) #self.log.info("LVAP after list : %s" % lvaplist[-1]) #Check if limit is not given and provide the default #if str(wtp.addr) not in linker.wtpdict_limit: #linker.wtpdict_limit[str(wtp.addr)]=linker.DEFAULT_LVAP_NUMBER_LIMIT #Check if wtp is not on the list and add it if str(wtp.addr) not in linker.wtpdict: linker.wtpdict[str(wtp.addr)] = lvaplist #If limit is -1 then wtp has no limit if linker.wtpdict_limit[str(wtp.addr)] == -1: self.log.info("################ WTP : %s has unlimited LVAPs (limit %f) %s ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)], linker.wtpdict[str(wtp.addr)])) continue #If wtp client limit is exceeded, then handover the excess lvaps to new wtp elif len(lvaplist) > linker.wtpdict_limit[str(wtp.addr)]: self.log.info("################ WTP : %s has more LVAPs than the limit %f ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)])) self.log.info(lvaplist) self.log.info(linker.wtpdict[str(wtp.addr)]) diff = [a for a in lvaplist+linker.wtpdict[str(wtp.addr)] if (a not in lvaplist) or (a not in linker.wtpdict[str(wtp.addr)])] self.log.info(diff) numoflvaptohandover=len(lvaplist) - linker.wtpdict_limit[str(wtp.addr)] self.log.info(numoflvaptohandover) for lvap in self.lvaps(): #If lvap is the extra lvap in wtp then find wtp with best rssi and handover to that if lvap.addr in diff or lvap.addr in lvaplist: self.log.info("If lvap in diff") # Initialize the Resource Pool pool = ResourcePool() # Update the Resource Pool with all # the available Resourse Blocks for other_wtp in self.wtps(): if other_wtp.addr != wtp.addr: if linker.wtpdict_limit[str(other_wtp.addr)] < len(linker.wtpdict[str(other_wtp.addr)]): self.log.info(linker.wtpdict_limit[str(other_wtp.addr)]) self.log.info(len(linker.wtpdict[str(other_wtp.addr)])) pool = pool | other_wtp.supports # Select matching Resource Blocks matches = pool & lvap.scheduled_on max_rssi = -float("inf") first_block=1; for block in matches: if first_block == 1: first_block=0 max_rssi=block.ucqm[lvap.addr]['mov_rssi'] else: if max_rssi < block.ucqm[lvap.addr]['mov_rssi']: max_rssi=block.ucqm[lvap.addr]['mov_rssi'] # Filter Resource Blocks by RSSI valid = [block for block in matches if block.ucqm[lvap.addr]['mov_rssi'] >= max_rssi] if not valid: self.log.info("not valid") continue for block in valid: self.log.info("valid LVAP: %s - Current RSSI : %.2f dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) #Remove from lvaplist lvaplist.remove(str(lvap.addr)) new_block = max(valid, key=lambda x: x.ucqm[lvap.addr]['mov_rssi']) self.log.info("LVAP %s setting new block %s" % (lvap.addr, new_block)) lvap.scheduled_on = new_block numoflvaptohandover=numoflvaptohandover-1 else: continue #if all lvaps have been handovered then break if numoflvaptohandover == 0: break else: self.log.info("################ WTP : %s has LVAPs' limit %f %s ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)], linker.wtpdict[str(wtp.addr)])) #Update lvaplist for given wtp linker.wtpdict[str(wtp.addr)] = lvaplist for wtp, lvaps in linker.wtpdict.items(): temp = None insert_comma = 0 for lvap in lvaps: if insert_comma == 0: temp = lvap insert_comma=1 continue temp = temp + ', ' + lvap #str(lvaps).strip('['']')#.strip('[EtherAddress'']') self.log.info("WTP : %s has %u LVAPs : %s\n" % (wtp, len(lvaps), temp)) #self.wtp_lvap_limit(wtp,lvaps) #if len(lvaps) > linker.DEFAULT_LVAP_NUMBER_LIMIT: #self.log.info("################WTP : %s has more LVAPs than the limit######################\n" % wtp) #for wtp in self.wtps() def lvap_timelimit(self): self.log.info("Running Time Limit...") self.log.info("DEFAULT_LVAP_TIME_LIMIT : %d" % linker.DEFAULT_LVAP_TIME_LIMIT) deletionlist = [] for lvap, endtime in linker.lvap_timer.items(): #self.log.info("LVAP") formated_endtime = datetime.datetime.strptime(endtime, '%Y-%m-%d %H:%M:%S') currenttime = datetime.datetime.now() if (currenttime - formated_endtime).total_seconds() >= 0: self.log.info("$$$$$$$$$$$$$ LVAP: %s Time ends" % lvap) deletionlist.append(lvap) else: self.log.info("$$$$$$$$$$$$$ LVAP: %s Time continues" % lvap) for dlvap in deletionlist: self.log.info("$$$$$$$$$$$$$ Removing Timer LVAP: %s" % dlvap) linker.removeLVAPTimer(self,dlvap) for lvap in self.lvaps(): if str(lvap.addr) == dlvap: lvaplabel=RUNTIME.get_label(lvap.addr) self.log.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$") #del lvap.downlink[lvap.block] #deletes lvap #del RUNTIME.lvaps[lvap.addr] for wtp in self.wtps(): if lvap.wtp.addr == wtp.addr: #wtp.connection.send_del_lvap(lvap) RUNTIME.remove_lvap(lvap.addr) temp = linker.wtpdict[str(wtp.addr)] temp.remove(str(lvap.addr)) #del RUNTIME.lvaps[lvap.addr] break #self.remove_lvap(lvap) lvaplabel=RUNTIME.get_label(lvap.addr) #self.log.info(lvaplabel) self.log.info("Deleting LVAP %s from db" % lvaplabel) self.log.info("Removing %s %s from allowed LVAPs" % (lvaplabel, lvap.addr)) RUNTIME.remove_allowed(lvap.addr) self.log.info("Adding %s %s to denied LVAPs" % (lvaplabel, lvap.addr)) RUNTIME.add_denied(lvap.addr,lvaplabel) self.log.info("LVAP %s deleted" % lvaplabel) break #pool = ResourcePool() #for lvap in self.lvaps(): # matches = pool # for block in matches: # self.log.info("zephyr : LVAP: %s - Current RSSI : %f dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) def loop(self): """ Periodic job. """ self.log.info("Periodic job.\n") self.log.info("Allowed LVAPs: %s" % (RUNTIME.allowed)) self.log.info("Denied LVAPs: %s\n" % (RUNTIME.denied)) if linker.initialize_limit == 1: for wtp in self.wtps(): #Check if limit is not given and provide the default if str(wtp.addr) not in linker.wtpdict_limit: linker.wtpdict_limit[str(wtp.addr)]=linker.DEFAULT_LVAP_NUMBER_LIMIT linker.initialize_limit = 0 self.log.info("Setting limit to default") self.wtp_clientlimit() self.lvap_timelimit() self.log.info("Current limit %u linker limit to %u" % (self.limit,linker.RSSI_LIMIT)) if self.limit != linker.RSSI_LIMIT: self.log.info("Current limit %u setting limit to %u" % (self.limit,linker.RSSI_LIMIT)) self.set_limit(linker.RSSI_LIMIT) # Handover every active LVAP to # the best WTP counterlvap=0 for lvap in self.lvaps(): self.handover(lvap) counterlvap=counterlvap+1 self.log.info("Active LVAPs: %u" % counterlvap) def launch(tenant_id, limit=linker.DEFAULT_RSSI_LIMIT, every=DEFAULT_PERIOD): """ Initialize the module. """ return Zephyr(tenant_id=tenant_id, limit=limit, every=every)
"""Called when a new WTP connects to the controller.""" for block in wtp.supports: self.ucqm(block=block, every=self.every)
identifier_body
zephyr.py
#!/usr/bin/env python3 # # Copyright (c) 2015, Roberto Riggio # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the CREATE-NET nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY CREATE-NET ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL CREATE-NET BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Basic Zephyr manager.""" from empower.core.app import EmpowerApp from empower.core.app import DEFAULT_PERIOD from empower.main import RUNTIME from empower.datatypes.etheraddress import EtherAddress from empower.core.resourcepool import ResourcePool from empower.lvapp.lvappconnection import LVAPPConnection import time, datetime, threading import empower.apps.zephyr.zephyrLinker as linker starttime = datetime.datetime.now() class Zephyr(EmpowerApp): """Basic mobility manager. Command Line Parameters: tenant_id: tenant id limit: handover limit in dBm (optional, default -80) every: loop period in ms (optional, default 5000ms) Example: ./empower-runtime.py apps.mobilitymanager.mobilitymanager \ --tenant_id=52313ecb-9d00-4b7d-b873-b55d3d9ada26 """ def __init__(self, **kwargs): self.__limit = linker.DEFAULT_RSSI_LIMIT EmpowerApp.__init__(self, **kwargs) # Register an wtp up event self.wtpup(callback=self.wtp_up_callback) # Register an lvap join event self.lvapjoin(callback=self.lvap_join_callback) # Register an lvap leave event self.lvapleave(callback=self.lvap_leave_callback) def lvap_leave_callback(self, lvap): """Called when an LVAP disassociates from a tennant.""" self.log.info("LVAP %s left %s" % (lvap.addr, lvap.ssid)) def wtp_up_callback(self, wtp): """Called when a new WTP connects to the controller."""
def lvap_join_callback(self, lvap): """Called when an joins the network.""" self.rssi(lvap=lvap.addr, value=self.limit, relation='LT', callback=self.low_rssi) def handover(self, lvap): """ Handover the LVAP to a WTP with an RSSI higher that -65dB. """ self.log.info("Running handover...") self.log.info("LVAP: %s - Limit RSSI : %u dB" % (lvap.addr, self.limit)) self.log.info("Initialize the Resource Pool") pool = ResourcePool() for wtp in self.wtps(): #for wtpd, lvaps in wtpdict.items(): #self.log.info("WTP in wtps : %s WTP in dict : %s are equal : %u\n" % (str(wtp.addr), wtpd, (wtp.addr == wtpd))) templist = linker.wtpdict[str(wtp.addr)] length = len(templist) self.log.info("Pooling WTP: %s" % str(wtp.addr)) self.log.info(wtp.supports) pool = pool | wtp.supports self.log.info("Select matching Resource Blocks") matches = pool #& lvap.scheduled_on self.log.info(matches) self.log.info("LVAP1 LOOP 107") counter=0 for lvap in self.lvaps(): self.log.info("!!!!!!!!!!!!!!!%d : %s" % (counter, lvap.addr)) counter=counter+1 for block in matches: self.log.info("Time : %f \n LVAP : %s \n addr : %s \n last_rssi_avg : %.2f \n last_rssi_std : %.2f \n last_packets : %u \n mov_rrsi : %.2f\n" % (time.time(), lvap.addr, block.ucqm[lvap.addr]['addr'], block.ucqm[lvap.addr]['last_rssi_avg'], block.ucqm[lvap.addr]['last_rssi_std'], block.ucqm[lvap.addr]['last_packets'], block.ucqm[lvap.addr]['mov_rssi'])) if (lvap.addr=="78:44:76:BF:DA:D4"): self.log.info("LVAP: %s is leaving" % lvap.addr) #del lvap.downlink[block] #deletes lvap # Initialize the Resource Pool pool = ResourcePool() # Update the Resource Pool with all # the available Resourse Blocks for wtp in self.wtps(): if (str(wtp.addr) in linker.wtpdict): if (len(linker.wtpdict[str(wtp.addr)]) < linker.wtpdict_limit[str(wtp.addr)]): pool = pool | wtp.supports # Select matching Resource Blocks matches = pool & lvap.scheduled_on # Filter Resource Blocks by RSSI valid = [block for block in matches if block.ucqm[lvap.addr]['mov_rssi'] >= self.limit] #valid = self.blocks(lvap, self.limit) if not valid: self.log.info("not valid") return for block in valid: self.log.info("valid LVAP: %s - Current RSSI : %u dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) new_block = max(valid, key=lambda x: x.ucqm[lvap.addr]['mov_rssi']) self.log.info("LVAP %s setting new block %s" % (lvap.addr, new_block)) lvap.scheduled_on = new_block @property def limit(self): """Return loop period.""" return self.__limit @limit.setter def limit(self, value): """Set limit.""" limit = int(value) if limit > 0 or limit < -100: raise ValueError("Invalid value for limit") self.log.info("Setting limit %u dB" % value) self.__limit = limit def set_limit(self, value): """Set limit.""" limit = int(value) if limit > 0 or limit < -100: raise ValueError("Invalid value for limit") self.log.info("Setting limit %u dB" % value) self.__limit = limit def low_rssi(self, trigger): """ Perform handover if an LVAP's rssi is going below the threshold. """ self.log.info("Received trigger from %s rssi %u dB", trigger.event['block'], trigger.event['current']) lvap = self.lvap(trigger.lvap) if not lvap: return self.handover(lvap) def wtp_clientlimit(self): self.log.info("Running Client Limit...") wtp_c=0 for wtp in self.wtps(): #Create lvaplist for the specific wtp lvaplist = [] for lvap in self.lvaps(): if lvap.wtp.addr == wtp.addr: #self.log.info("LVAP before list : %s" % lvap.addr) lvaplist.append(str(lvap.addr)) #self.log.info("LVAP after list : %s" % lvaplist[-1]) #Check if limit is not given and provide the default #if str(wtp.addr) not in linker.wtpdict_limit: #linker.wtpdict_limit[str(wtp.addr)]=linker.DEFAULT_LVAP_NUMBER_LIMIT #Check if wtp is not on the list and add it if str(wtp.addr) not in linker.wtpdict: linker.wtpdict[str(wtp.addr)] = lvaplist #If limit is -1 then wtp has no limit if linker.wtpdict_limit[str(wtp.addr)] == -1: self.log.info("################ WTP : %s has unlimited LVAPs (limit %f) %s ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)], linker.wtpdict[str(wtp.addr)])) continue #If wtp client limit is exceeded, then handover the excess lvaps to new wtp elif len(lvaplist) > linker.wtpdict_limit[str(wtp.addr)]: self.log.info("################ WTP : %s has more LVAPs than the limit %f ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)])) self.log.info(lvaplist) self.log.info(linker.wtpdict[str(wtp.addr)]) diff = [a for a in lvaplist+linker.wtpdict[str(wtp.addr)] if (a not in lvaplist) or (a not in linker.wtpdict[str(wtp.addr)])] self.log.info(diff) numoflvaptohandover=len(lvaplist) - linker.wtpdict_limit[str(wtp.addr)] self.log.info(numoflvaptohandover) for lvap in self.lvaps(): #If lvap is the extra lvap in wtp then find wtp with best rssi and handover to that if lvap.addr in diff or lvap.addr in lvaplist: self.log.info("If lvap in diff") # Initialize the Resource Pool pool = ResourcePool() # Update the Resource Pool with all # the available Resourse Blocks for other_wtp in self.wtps(): if other_wtp.addr != wtp.addr: if linker.wtpdict_limit[str(other_wtp.addr)] < len(linker.wtpdict[str(other_wtp.addr)]): self.log.info(linker.wtpdict_limit[str(other_wtp.addr)]) self.log.info(len(linker.wtpdict[str(other_wtp.addr)])) pool = pool | other_wtp.supports # Select matching Resource Blocks matches = pool & lvap.scheduled_on max_rssi = -float("inf") first_block=1; for block in matches: if first_block == 1: first_block=0 max_rssi=block.ucqm[lvap.addr]['mov_rssi'] else: if max_rssi < block.ucqm[lvap.addr]['mov_rssi']: max_rssi=block.ucqm[lvap.addr]['mov_rssi'] # Filter Resource Blocks by RSSI valid = [block for block in matches if block.ucqm[lvap.addr]['mov_rssi'] >= max_rssi] if not valid: self.log.info("not valid") continue for block in valid: self.log.info("valid LVAP: %s - Current RSSI : %.2f dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) #Remove from lvaplist lvaplist.remove(str(lvap.addr)) new_block = max(valid, key=lambda x: x.ucqm[lvap.addr]['mov_rssi']) self.log.info("LVAP %s setting new block %s" % (lvap.addr, new_block)) lvap.scheduled_on = new_block numoflvaptohandover=numoflvaptohandover-1 else: continue #if all lvaps have been handovered then break if numoflvaptohandover == 0: break else: self.log.info("################ WTP : %s has LVAPs' limit %f %s ######################\n" % (wtp, linker.wtpdict_limit[str(wtp.addr)], linker.wtpdict[str(wtp.addr)])) #Update lvaplist for given wtp linker.wtpdict[str(wtp.addr)] = lvaplist for wtp, lvaps in linker.wtpdict.items(): temp = None insert_comma = 0 for lvap in lvaps: if insert_comma == 0: temp = lvap insert_comma=1 continue temp = temp + ', ' + lvap #str(lvaps).strip('['']')#.strip('[EtherAddress'']') self.log.info("WTP : %s has %u LVAPs : %s\n" % (wtp, len(lvaps), temp)) #self.wtp_lvap_limit(wtp,lvaps) #if len(lvaps) > linker.DEFAULT_LVAP_NUMBER_LIMIT: #self.log.info("################WTP : %s has more LVAPs than the limit######################\n" % wtp) #for wtp in self.wtps() def lvap_timelimit(self): self.log.info("Running Time Limit...") self.log.info("DEFAULT_LVAP_TIME_LIMIT : %d" % linker.DEFAULT_LVAP_TIME_LIMIT) deletionlist = [] for lvap, endtime in linker.lvap_timer.items(): #self.log.info("LVAP") formated_endtime = datetime.datetime.strptime(endtime, '%Y-%m-%d %H:%M:%S') currenttime = datetime.datetime.now() if (currenttime - formated_endtime).total_seconds() >= 0: self.log.info("$$$$$$$$$$$$$ LVAP: %s Time ends" % lvap) deletionlist.append(lvap) else: self.log.info("$$$$$$$$$$$$$ LVAP: %s Time continues" % lvap) for dlvap in deletionlist: self.log.info("$$$$$$$$$$$$$ Removing Timer LVAP: %s" % dlvap) linker.removeLVAPTimer(self,dlvap) for lvap in self.lvaps(): if str(lvap.addr) == dlvap: lvaplabel=RUNTIME.get_label(lvap.addr) self.log.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$") #del lvap.downlink[lvap.block] #deletes lvap #del RUNTIME.lvaps[lvap.addr] for wtp in self.wtps(): if lvap.wtp.addr == wtp.addr: #wtp.connection.send_del_lvap(lvap) RUNTIME.remove_lvap(lvap.addr) temp = linker.wtpdict[str(wtp.addr)] temp.remove(str(lvap.addr)) #del RUNTIME.lvaps[lvap.addr] break #self.remove_lvap(lvap) lvaplabel=RUNTIME.get_label(lvap.addr) #self.log.info(lvaplabel) self.log.info("Deleting LVAP %s from db" % lvaplabel) self.log.info("Removing %s %s from allowed LVAPs" % (lvaplabel, lvap.addr)) RUNTIME.remove_allowed(lvap.addr) self.log.info("Adding %s %s to denied LVAPs" % (lvaplabel, lvap.addr)) RUNTIME.add_denied(lvap.addr,lvaplabel) self.log.info("LVAP %s deleted" % lvaplabel) break #pool = ResourcePool() #for lvap in self.lvaps(): # matches = pool # for block in matches: # self.log.info("zephyr : LVAP: %s - Current RSSI : %f dB" % (lvap.addr, float(block.ucqm[lvap.addr]['mov_rssi']))) def loop(self): """ Periodic job. """ self.log.info("Periodic job.\n") self.log.info("Allowed LVAPs: %s" % (RUNTIME.allowed)) self.log.info("Denied LVAPs: %s\n" % (RUNTIME.denied)) if linker.initialize_limit == 1: for wtp in self.wtps(): #Check if limit is not given and provide the default if str(wtp.addr) not in linker.wtpdict_limit: linker.wtpdict_limit[str(wtp.addr)]=linker.DEFAULT_LVAP_NUMBER_LIMIT linker.initialize_limit = 0 self.log.info("Setting limit to default") self.wtp_clientlimit() self.lvap_timelimit() self.log.info("Current limit %u linker limit to %u" % (self.limit,linker.RSSI_LIMIT)) if self.limit != linker.RSSI_LIMIT: self.log.info("Current limit %u setting limit to %u" % (self.limit,linker.RSSI_LIMIT)) self.set_limit(linker.RSSI_LIMIT) # Handover every active LVAP to # the best WTP counterlvap=0 for lvap in self.lvaps(): self.handover(lvap) counterlvap=counterlvap+1 self.log.info("Active LVAPs: %u" % counterlvap) def launch(tenant_id, limit=linker.DEFAULT_RSSI_LIMIT, every=DEFAULT_PERIOD): """ Initialize the module. """ return Zephyr(tenant_id=tenant_id, limit=limit, every=every)
for block in wtp.supports: self.ucqm(block=block, every=self.every)
random_line_split
readers.py
""" DataReader code lives here. All DataReader classes should extend DataReader and implement the following methods: - help() - get_data() """ from datetime import datetime import requests class DataReader(object): """ Class-level constants that can be defined in code until we get around to putting them into a database table """ TARGET_URL = None DATA_TYPE = None RETURN_FORMAT = None # This is a help-feature for help() method def __init__(self): pass def help(self): return self.RETURN_FORMAT class USGSDataReader(DataReader): TARGET_URL = "http://waterservices.usgs.gov/nwis/iv/?format={}&sites={}&parameterCd={}" DATA_TYPE = "json" USGS_CODE_FLOW = '00060' USGS_CODE_LEVEL = '00065' def __init__(self): super(USGSDataReader, self).__init__() pass def get_data(self, uri): """ Hit USGS API and retrieve JSON object. Return GaugeData JSON object. :param uri: USGS id of the gauge being queried :returns: <GaugeData>: updated values in the form of a JSON object """ usgs_code = '0' * (8 - len(str(uri))) + str(uri) params = self.USGS_CODE_LEVEL + ',' + self.USGS_CODE_FLOW usgs_url = self.TARGET_URL.format(self.DATA_TYPE, usgs_code, params) result = requests.get(usgs_url).json() data = result["value"]["timeSeries"] output = { x["variable"]["variableCode"][0]["value"]: x["values"][0]["value"][0] for x in data } flow, level = None, None if "00060" in output.keys(): flow = output["00060"]["value"] if "00065" in output.keys(): level = output["00065"]["value"] package = {"gauge_id": uri, "timestamp": datetime.strptime( output["00065"]["dateTime"][:18], "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"), "level": level, "flow_cfs": flow} return package class WundergroundReader(DataReader): TARGET_URL = "http://api.wunderground.com/api/{}/geolookup/conditions/q/{}/{}.json" def __init__(self): super(WundergroundReader, self).__init__() pass def
(self, uri): """ Hit Wunderground API and retrieve JSON object. Return GaugeData object. :param uri : this is the gauge being queried :returns: <GaugeData>: updated values in the form of a GaugeData object """
get_data
identifier_name
readers.py
""" DataReader code lives here. All DataReader classes should extend DataReader and implement the following methods: - help() - get_data() """ from datetime import datetime import requests class DataReader(object): """ Class-level constants that can be defined in code until we get around to putting them into a database table """ TARGET_URL = None DATA_TYPE = None RETURN_FORMAT = None # This is a help-feature for help() method def __init__(self): pass def help(self): return self.RETURN_FORMAT class USGSDataReader(DataReader): TARGET_URL = "http://waterservices.usgs.gov/nwis/iv/?format={}&sites={}&parameterCd={}" DATA_TYPE = "json" USGS_CODE_FLOW = '00060' USGS_CODE_LEVEL = '00065' def __init__(self): super(USGSDataReader, self).__init__() pass def get_data(self, uri): """ Hit USGS API and retrieve JSON object. Return GaugeData JSON object. :param uri: USGS id of the gauge being queried :returns: <GaugeData>: updated values in the form of a JSON object """ usgs_code = '0' * (8 - len(str(uri))) + str(uri) params = self.USGS_CODE_LEVEL + ',' + self.USGS_CODE_FLOW usgs_url = self.TARGET_URL.format(self.DATA_TYPE, usgs_code, params) result = requests.get(usgs_url).json() data = result["value"]["timeSeries"] output = { x["variable"]["variableCode"][0]["value"]: x["values"][0]["value"][0] for x in data } flow, level = None, None if "00060" in output.keys(): flow = output["00060"]["value"] if "00065" in output.keys():
package = {"gauge_id": uri, "timestamp": datetime.strptime( output["00065"]["dateTime"][:18], "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"), "level": level, "flow_cfs": flow} return package class WundergroundReader(DataReader): TARGET_URL = "http://api.wunderground.com/api/{}/geolookup/conditions/q/{}/{}.json" def __init__(self): super(WundergroundReader, self).__init__() pass def get_data(self, uri): """ Hit Wunderground API and retrieve JSON object. Return GaugeData object. :param uri : this is the gauge being queried :returns: <GaugeData>: updated values in the form of a GaugeData object """
level = output["00065"]["value"]
conditional_block
readers.py
""" DataReader code lives here. All DataReader classes should extend DataReader and implement the following methods: - help() - get_data() """ from datetime import datetime import requests class DataReader(object): """ Class-level constants that can be defined in code until we get around to putting them into a database table """ TARGET_URL = None DATA_TYPE = None RETURN_FORMAT = None # This is a help-feature for help() method def __init__(self):
def help(self): return self.RETURN_FORMAT class USGSDataReader(DataReader): TARGET_URL = "http://waterservices.usgs.gov/nwis/iv/?format={}&sites={}&parameterCd={}" DATA_TYPE = "json" USGS_CODE_FLOW = '00060' USGS_CODE_LEVEL = '00065' def __init__(self): super(USGSDataReader, self).__init__() pass def get_data(self, uri): """ Hit USGS API and retrieve JSON object. Return GaugeData JSON object. :param uri: USGS id of the gauge being queried :returns: <GaugeData>: updated values in the form of a JSON object """ usgs_code = '0' * (8 - len(str(uri))) + str(uri) params = self.USGS_CODE_LEVEL + ',' + self.USGS_CODE_FLOW usgs_url = self.TARGET_URL.format(self.DATA_TYPE, usgs_code, params) result = requests.get(usgs_url).json() data = result["value"]["timeSeries"] output = { x["variable"]["variableCode"][0]["value"]: x["values"][0]["value"][0] for x in data } flow, level = None, None if "00060" in output.keys(): flow = output["00060"]["value"] if "00065" in output.keys(): level = output["00065"]["value"] package = {"gauge_id": uri, "timestamp": datetime.strptime( output["00065"]["dateTime"][:18], "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"), "level": level, "flow_cfs": flow} return package class WundergroundReader(DataReader): TARGET_URL = "http://api.wunderground.com/api/{}/geolookup/conditions/q/{}/{}.json" def __init__(self): super(WundergroundReader, self).__init__() pass def get_data(self, uri): """ Hit Wunderground API and retrieve JSON object. Return GaugeData object. :param uri : this is the gauge being queried :returns: <GaugeData>: updated values in the form of a GaugeData object """
pass
identifier_body
readers.py
""" DataReader code lives here. All DataReader classes should extend DataReader and implement the following methods: - help() - get_data() """ from datetime import datetime import requests class DataReader(object): """ Class-level constants that can be defined in code until we get around to putting them into a database table """ TARGET_URL = None DATA_TYPE = None RETURN_FORMAT = None # This is a help-feature for help() method def __init__(self): pass def help(self): return self.RETURN_FORMAT class USGSDataReader(DataReader): TARGET_URL = "http://waterservices.usgs.gov/nwis/iv/?format={}&sites={}&parameterCd={}" DATA_TYPE = "json" USGS_CODE_FLOW = '00060' USGS_CODE_LEVEL = '00065' def __init__(self): super(USGSDataReader, self).__init__() pass def get_data(self, uri): """ Hit USGS API and retrieve JSON object. Return GaugeData JSON object. :param uri: USGS id of the gauge being queried :returns: <GaugeData>: updated values in the form of a JSON object """ usgs_code = '0' * (8 - len(str(uri))) + str(uri) params = self.USGS_CODE_LEVEL + ',' + self.USGS_CODE_FLOW usgs_url = self.TARGET_URL.format(self.DATA_TYPE, usgs_code, params) result = requests.get(usgs_url).json() data = result["value"]["timeSeries"] output = { x["variable"]["variableCode"][0]["value"]: x["values"][0]["value"][0] for x in data } flow, level = None, None if "00060" in output.keys(): flow = output["00060"]["value"] if "00065" in output.keys(): level = output["00065"]["value"]
output["00065"]["dateTime"][:18], "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"), "level": level, "flow_cfs": flow} return package class WundergroundReader(DataReader): TARGET_URL = "http://api.wunderground.com/api/{}/geolookup/conditions/q/{}/{}.json" def __init__(self): super(WundergroundReader, self).__init__() pass def get_data(self, uri): """ Hit Wunderground API and retrieve JSON object. Return GaugeData object. :param uri : this is the gauge being queried :returns: <GaugeData>: updated values in the form of a GaugeData object """
package = {"gauge_id": uri, "timestamp": datetime.strptime(
random_line_split
test.py
from nose.tools import with_setup import os import hk_glazer as js2deg import subprocess import json class TestClass: @classmethod def setup_class(cls): cls.here = os.path.dirname(__file__) cls.data = cls.here + '/data' def test_1(self): '''Test 1: Check that json_to_degree works when imported''' with open(self.data + "/json_test_in.json") as config_file: config_dict = json.load(config_file) gen_str = js2deg.dict_to_dat(config_dict) with open(self.data + "/json_test_out.txt") as verif_file: test_str = verif_file.read() assert(test_str == gen_str) pass def test_2(self): '''Test 2: Check command line execution when saving to file''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') print(cmd) subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"]) with open("test2.txt") as file: gen_str = file.read() with open(self.data + "/json_test_out.txt") as file: test_str = file.read() assert(test_str == gen_str) os.remove("test2.txt") pass def test_3(self): '''Test 3: Command line execution when outfile already exists''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"]) try: subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"]) except Exception as e: #print(type(e)) assert(type(e) == subprocess.CalledProcessError) pass else:
finally: os.remove("test3.txt")
assert(False)
conditional_block
test.py
from nose.tools import with_setup import os import hk_glazer as js2deg import subprocess import json
cls.here = os.path.dirname(__file__) cls.data = cls.here + '/data' def test_1(self): '''Test 1: Check that json_to_degree works when imported''' with open(self.data + "/json_test_in.json") as config_file: config_dict = json.load(config_file) gen_str = js2deg.dict_to_dat(config_dict) with open(self.data + "/json_test_out.txt") as verif_file: test_str = verif_file.read() assert(test_str == gen_str) pass def test_2(self): '''Test 2: Check command line execution when saving to file''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') print(cmd) subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"]) with open("test2.txt") as file: gen_str = file.read() with open(self.data + "/json_test_out.txt") as file: test_str = file.read() assert(test_str == gen_str) os.remove("test2.txt") pass def test_3(self): '''Test 3: Command line execution when outfile already exists''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"]) try: subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"]) except Exception as e: #print(type(e)) assert(type(e) == subprocess.CalledProcessError) pass else: assert(False) finally: os.remove("test3.txt")
class TestClass: @classmethod def setup_class(cls):
random_line_split
test.py
from nose.tools import with_setup import os import hk_glazer as js2deg import subprocess import json class TestClass: @classmethod def setup_class(cls): cls.here = os.path.dirname(__file__) cls.data = cls.here + '/data' def test_1(self): '''Test 1: Check that json_to_degree works when imported''' with open(self.data + "/json_test_in.json") as config_file: config_dict = json.load(config_file) gen_str = js2deg.dict_to_dat(config_dict) with open(self.data + "/json_test_out.txt") as verif_file: test_str = verif_file.read() assert(test_str == gen_str) pass def
(self): '''Test 2: Check command line execution when saving to file''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') print(cmd) subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"]) with open("test2.txt") as file: gen_str = file.read() with open(self.data + "/json_test_out.txt") as file: test_str = file.read() assert(test_str == gen_str) os.remove("test2.txt") pass def test_3(self): '''Test 3: Command line execution when outfile already exists''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"]) try: subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"]) except Exception as e: #print(type(e)) assert(type(e) == subprocess.CalledProcessError) pass else: assert(False) finally: os.remove("test3.txt")
test_2
identifier_name
test.py
from nose.tools import with_setup import os import hk_glazer as js2deg import subprocess import json class TestClass: @classmethod def setup_class(cls): cls.here = os.path.dirname(__file__) cls.data = cls.here + '/data' def test_1(self): '''Test 1: Check that json_to_degree works when imported''' with open(self.data + "/json_test_in.json") as config_file: config_dict = json.load(config_file) gen_str = js2deg.dict_to_dat(config_dict) with open(self.data + "/json_test_out.txt") as verif_file: test_str = verif_file.read() assert(test_str == gen_str) pass def test_2(self):
def test_3(self): '''Test 3: Command line execution when outfile already exists''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"]) try: subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"]) except Exception as e: #print(type(e)) assert(type(e) == subprocess.CalledProcessError) pass else: assert(False) finally: os.remove("test3.txt")
'''Test 2: Check command line execution when saving to file''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') print(cmd) subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"]) with open("test2.txt") as file: gen_str = file.read() with open(self.data + "/json_test_out.txt") as file: test_str = file.read() assert(test_str == gen_str) os.remove("test2.txt") pass
identifier_body
environment.prod.ts
/** * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const environment = { production: true, firebase: { apiKey: '{YOUR_API_KEY}', authDomain: 'yourproject.firebaseapp.com', databaseURL: 'https://yourproject.firebaseio.com', projectId: '{YOUR_PROJECT_ID}', storageBucket: 'undefined', messagingSenderId: '{YOUR_MESSAGING_SENDER_ID}', appId: '{YOUR_APP_ID}', measurementId: '{YOUR_MEASUREMENT_ID}', }, };
random_line_split
shardcounter_sync.py
import random from google.appengine.api import memcache from google.appengine.ext import ndb SHARD_KEY_TEMPLATE = 'shard-{}-{:d}' class GeneralCounterShardConfig(ndb.Model): num_shards = ndb.IntegerProperty(default=20) @classmethod def all_keys(cls, name): config = cls.get_or_insert(name) shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)] return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings] class GeneralCounterShard(ndb.Model): count = ndb.IntegerProperty(default=0) def get_count(name): total = memcache.get(name)
parent_key = ndb.Key('ShardCounterParent', name) shard_query = GeneralCounterShard.query(ancestor=parent_key) shard_counters = shard_query.fetch(limit=None) for counter in shard_counters: if counter is not None: total += counter.count memcache.add(name, total, 7200) # 2 hours to expire return total def increment(name): config = GeneralCounterShardConfig.get_or_insert(name) return _increment(name, config.num_shards) @ndb.transactional def _increment(name, num_shards): index = random.randint(0, num_shards - 1) shard_key_string = SHARD_KEY_TEMPLATE.format(name, index) parent_key = ndb.Key('ShardCounterParent', name) counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key) if counter is None: counter = GeneralCounterShard(parent = parent_key, id=shard_key_string) counter.count += 1 counter.put() rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache if rval is None: return get_count(name) return rval @ndb.transactional def increase_shards(name, num_shards): config = GeneralCounterShardConfig.get_or_insert(name) if config.num_shards < num_shards: config.num_shards = num_shards config.put()
if total is None: total = 0
random_line_split
shardcounter_sync.py
import random from google.appengine.api import memcache from google.appengine.ext import ndb SHARD_KEY_TEMPLATE = 'shard-{}-{:d}' class GeneralCounterShardConfig(ndb.Model): num_shards = ndb.IntegerProperty(default=20) @classmethod def all_keys(cls, name): config = cls.get_or_insert(name) shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)] return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings] class GeneralCounterShard(ndb.Model): count = ndb.IntegerProperty(default=0) def get_count(name): total = memcache.get(name) if total is None: total = 0 parent_key = ndb.Key('ShardCounterParent', name) shard_query = GeneralCounterShard.query(ancestor=parent_key) shard_counters = shard_query.fetch(limit=None) for counter in shard_counters: if counter is not None: total += counter.count memcache.add(name, total, 7200) # 2 hours to expire return total def increment(name):
@ndb.transactional def _increment(name, num_shards): index = random.randint(0, num_shards - 1) shard_key_string = SHARD_KEY_TEMPLATE.format(name, index) parent_key = ndb.Key('ShardCounterParent', name) counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key) if counter is None: counter = GeneralCounterShard(parent = parent_key, id=shard_key_string) counter.count += 1 counter.put() rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache if rval is None: return get_count(name) return rval @ndb.transactional def increase_shards(name, num_shards): config = GeneralCounterShardConfig.get_or_insert(name) if config.num_shards < num_shards: config.num_shards = num_shards config.put()
config = GeneralCounterShardConfig.get_or_insert(name) return _increment(name, config.num_shards)
identifier_body
shardcounter_sync.py
import random from google.appengine.api import memcache from google.appengine.ext import ndb SHARD_KEY_TEMPLATE = 'shard-{}-{:d}' class GeneralCounterShardConfig(ndb.Model): num_shards = ndb.IntegerProperty(default=20) @classmethod def all_keys(cls, name): config = cls.get_or_insert(name) shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)] return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings] class GeneralCounterShard(ndb.Model): count = ndb.IntegerProperty(default=0) def get_count(name): total = memcache.get(name) if total is None: total = 0 parent_key = ndb.Key('ShardCounterParent', name) shard_query = GeneralCounterShard.query(ancestor=parent_key) shard_counters = shard_query.fetch(limit=None) for counter in shard_counters: if counter is not None: total += counter.count memcache.add(name, total, 7200) # 2 hours to expire return total def increment(name): config = GeneralCounterShardConfig.get_or_insert(name) return _increment(name, config.num_shards) @ndb.transactional def _increment(name, num_shards): index = random.randint(0, num_shards - 1) shard_key_string = SHARD_KEY_TEMPLATE.format(name, index) parent_key = ndb.Key('ShardCounterParent', name) counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key) if counter is None: counter = GeneralCounterShard(parent = parent_key, id=shard_key_string) counter.count += 1 counter.put() rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache if rval is None:
return rval @ndb.transactional def increase_shards(name, num_shards): config = GeneralCounterShardConfig.get_or_insert(name) if config.num_shards < num_shards: config.num_shards = num_shards config.put()
return get_count(name)
conditional_block
shardcounter_sync.py
import random from google.appengine.api import memcache from google.appengine.ext import ndb SHARD_KEY_TEMPLATE = 'shard-{}-{:d}' class GeneralCounterShardConfig(ndb.Model): num_shards = ndb.IntegerProperty(default=20) @classmethod def all_keys(cls, name): config = cls.get_or_insert(name) shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)] return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings] class GeneralCounterShard(ndb.Model): count = ndb.IntegerProperty(default=0) def
(name): total = memcache.get(name) if total is None: total = 0 parent_key = ndb.Key('ShardCounterParent', name) shard_query = GeneralCounterShard.query(ancestor=parent_key) shard_counters = shard_query.fetch(limit=None) for counter in shard_counters: if counter is not None: total += counter.count memcache.add(name, total, 7200) # 2 hours to expire return total def increment(name): config = GeneralCounterShardConfig.get_or_insert(name) return _increment(name, config.num_shards) @ndb.transactional def _increment(name, num_shards): index = random.randint(0, num_shards - 1) shard_key_string = SHARD_KEY_TEMPLATE.format(name, index) parent_key = ndb.Key('ShardCounterParent', name) counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key) if counter is None: counter = GeneralCounterShard(parent = parent_key, id=shard_key_string) counter.count += 1 counter.put() rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache if rval is None: return get_count(name) return rval @ndb.transactional def increase_shards(name, num_shards): config = GeneralCounterShardConfig.get_or_insert(name) if config.num_shards < num_shards: config.num_shards = num_shards config.put()
get_count
identifier_name
testrunprogram.py
import unittest import sys import os sys.path.append('bin') from umdinst import wrap class TestRunProgram(unittest.TestCase): def setUp(self): self.tempfilename = 'emptyfile' # This is in createfile.sh self.failIf(os.path.exists(self.tempfilename)) # Find the "touch" program if os.path.exists('/usr/bin/touch'): self.touchprog = '/usr/bin/touch' elif os.path.exists('/bin/touch'): self.touchprog = '/bin/touch' else: raise ValueError, "Cannot locate the 'touch' program, which is needed for testing" # Build a "failing" program, that just returns non-zero status status = os.system("gcc -o fail test/testsource/fail.c") self.failIf(status!=0) self.failprog = './fail' # Build a "succeeding" program, that returns zero status status = os.system("gcc -o success test/testsource/success.c") self.failIf(status!=0) self.successprog = './success' def tearDown(self):
def testRunWithArgs(self): prog = self.touchprog # Make sure the file doesn't exist self.failIf(os.path.exists(self.tempfilename)) # Create a temporary file args = [self.tempfilename] wrap.run(prog,args) self.failUnless(os.path.exists(self.tempfilename)) def testRunNoArgs(self): # Run a program with no arguments os.chmod('test/testsource/createfile.sh',0755) s = wrap.run('test/testsource/createfile.sh',[]) self.failUnless(os.path.exists(self.tempfilename)) def testRunSuccess(self): # Run a program that succeeds s = wrap.run(self.successprog,[self.successprog]) self.failUnless(s) def testRunFailure(self): # Runa program that fails and test for failure s = wrap.run(self.failprog,[self.failprog]) self.failIf(s) if __name__ == '__main__': unittest.main()
if os.path.exists(self.tempfilename): os.unlink(self.tempfilename)
identifier_body
testrunprogram.py
import unittest import sys import os sys.path.append('bin') from umdinst import wrap class TestRunProgram(unittest.TestCase): def setUp(self): self.tempfilename = 'emptyfile' # This is in createfile.sh self.failIf(os.path.exists(self.tempfilename)) # Find the "touch" program if os.path.exists('/usr/bin/touch'): self.touchprog = '/usr/bin/touch' elif os.path.exists('/bin/touch'): self.touchprog = '/bin/touch' else: raise ValueError, "Cannot locate the 'touch' program, which is needed for testing" # Build a "failing" program, that just returns non-zero status status = os.system("gcc -o fail test/testsource/fail.c") self.failIf(status!=0) self.failprog = './fail'
self.failIf(status!=0) self.successprog = './success' def tearDown(self): if os.path.exists(self.tempfilename): os.unlink(self.tempfilename) def testRunWithArgs(self): prog = self.touchprog # Make sure the file doesn't exist self.failIf(os.path.exists(self.tempfilename)) # Create a temporary file args = [self.tempfilename] wrap.run(prog,args) self.failUnless(os.path.exists(self.tempfilename)) def testRunNoArgs(self): # Run a program with no arguments os.chmod('test/testsource/createfile.sh',0755) s = wrap.run('test/testsource/createfile.sh',[]) self.failUnless(os.path.exists(self.tempfilename)) def testRunSuccess(self): # Run a program that succeeds s = wrap.run(self.successprog,[self.successprog]) self.failUnless(s) def testRunFailure(self): # Runa program that fails and test for failure s = wrap.run(self.failprog,[self.failprog]) self.failIf(s) if __name__ == '__main__': unittest.main()
# Build a "succeeding" program, that returns zero status status = os.system("gcc -o success test/testsource/success.c")
random_line_split
testrunprogram.py
import unittest import sys import os sys.path.append('bin') from umdinst import wrap class TestRunProgram(unittest.TestCase): def setUp(self): self.tempfilename = 'emptyfile' # This is in createfile.sh self.failIf(os.path.exists(self.tempfilename)) # Find the "touch" program if os.path.exists('/usr/bin/touch'): self.touchprog = '/usr/bin/touch' elif os.path.exists('/bin/touch'): self.touchprog = '/bin/touch' else:
# Build a "failing" program, that just returns non-zero status status = os.system("gcc -o fail test/testsource/fail.c") self.failIf(status!=0) self.failprog = './fail' # Build a "succeeding" program, that returns zero status status = os.system("gcc -o success test/testsource/success.c") self.failIf(status!=0) self.successprog = './success' def tearDown(self): if os.path.exists(self.tempfilename): os.unlink(self.tempfilename) def testRunWithArgs(self): prog = self.touchprog # Make sure the file doesn't exist self.failIf(os.path.exists(self.tempfilename)) # Create a temporary file args = [self.tempfilename] wrap.run(prog,args) self.failUnless(os.path.exists(self.tempfilename)) def testRunNoArgs(self): # Run a program with no arguments os.chmod('test/testsource/createfile.sh',0755) s = wrap.run('test/testsource/createfile.sh',[]) self.failUnless(os.path.exists(self.tempfilename)) def testRunSuccess(self): # Run a program that succeeds s = wrap.run(self.successprog,[self.successprog]) self.failUnless(s) def testRunFailure(self): # Runa program that fails and test for failure s = wrap.run(self.failprog,[self.failprog]) self.failIf(s) if __name__ == '__main__': unittest.main()
raise ValueError, "Cannot locate the 'touch' program, which is needed for testing"
conditional_block
testrunprogram.py
import unittest import sys import os sys.path.append('bin') from umdinst import wrap class TestRunProgram(unittest.TestCase): def setUp(self): self.tempfilename = 'emptyfile' # This is in createfile.sh self.failIf(os.path.exists(self.tempfilename)) # Find the "touch" program if os.path.exists('/usr/bin/touch'): self.touchprog = '/usr/bin/touch' elif os.path.exists('/bin/touch'): self.touchprog = '/bin/touch' else: raise ValueError, "Cannot locate the 'touch' program, which is needed for testing" # Build a "failing" program, that just returns non-zero status status = os.system("gcc -o fail test/testsource/fail.c") self.failIf(status!=0) self.failprog = './fail' # Build a "succeeding" program, that returns zero status status = os.system("gcc -o success test/testsource/success.c") self.failIf(status!=0) self.successprog = './success' def tearDown(self): if os.path.exists(self.tempfilename): os.unlink(self.tempfilename) def testRunWithArgs(self): prog = self.touchprog # Make sure the file doesn't exist self.failIf(os.path.exists(self.tempfilename)) # Create a temporary file args = [self.tempfilename] wrap.run(prog,args) self.failUnless(os.path.exists(self.tempfilename)) def testRunNoArgs(self): # Run a program with no arguments os.chmod('test/testsource/createfile.sh',0755) s = wrap.run('test/testsource/createfile.sh',[]) self.failUnless(os.path.exists(self.tempfilename)) def
(self): # Run a program that succeeds s = wrap.run(self.successprog,[self.successprog]) self.failUnless(s) def testRunFailure(self): # Runa program that fails and test for failure s = wrap.run(self.failprog,[self.failprog]) self.failIf(s) if __name__ == '__main__': unittest.main()
testRunSuccess
identifier_name
transaction.ts
import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types'; /** Add node transaction to the event */ export class Transaction implements Integration { /** * @inheritDoc */ public name: string = Transaction.id; /** * @inheritDoc */ public static id: string = 'Transaction'; /** * @inheritDoc */ public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { addGlobalEventProcessor(event => { const self = getCurrentHub().getIntegration(Transaction); if (self)
return event; }); } /** * @inheritDoc */ public process(event: Event): Event { const frames = this._getFramesFromEvent(event); // use for loop so we don't have to reverse whole frames array for (let i = frames.length - 1; i >= 0; i--) { const frame = frames[i]; if (frame.in_app === true) { event.transaction = this._getTransaction(frame); break; } } return event; } /** JSDoc */ private _getFramesFromEvent(event: Event): StackFrame[] { const exception = event.exception && event.exception.values && event.exception.values[0]; return (exception && exception.stacktrace && exception.stacktrace.frames) || []; } /** JSDoc */ private _getTransaction(frame: StackFrame): string { return frame.module || frame.function ? `${frame.module || '?'}/${frame.function || '?'}` : '<unknown>'; } }
{ return self.process(event); }
conditional_block
transaction.ts
import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types'; /** Add node transaction to the event */ export class Transaction implements Integration { /** * @inheritDoc */ public name: string = Transaction.id; /** * @inheritDoc */ public static id: string = 'Transaction'; /** * @inheritDoc */ public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { addGlobalEventProcessor(event => { const self = getCurrentHub().getIntegration(Transaction); if (self) { return self.process(event); } return event; }); } /** * @inheritDoc */ public process(event: Event): Event { const frames = this._getFramesFromEvent(event); // use for loop so we don't have to reverse whole frames array for (let i = frames.length - 1; i >= 0; i--) { const frame = frames[i]; if (frame.in_app === true) { event.transaction = this._getTransaction(frame); break; } } return event; } /** JSDoc */ private _getFramesFromEvent(event: Event): StackFrame[] { const exception = event.exception && event.exception.values && event.exception.values[0]; return (exception && exception.stacktrace && exception.stacktrace.frames) || []; } /** JSDoc */ private
(frame: StackFrame): string { return frame.module || frame.function ? `${frame.module || '?'}/${frame.function || '?'}` : '<unknown>'; } }
_getTransaction
identifier_name
transaction.ts
import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types'; /** Add node transaction to the event */ export class Transaction implements Integration { /** * @inheritDoc */ public name: string = Transaction.id; /** * @inheritDoc */ public static id: string = 'Transaction'; /** * @inheritDoc */ public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { addGlobalEventProcessor(event => { const self = getCurrentHub().getIntegration(Transaction); if (self) { return self.process(event); } return event; }); } /** * @inheritDoc */ public process(event: Event): Event { const frames = this._getFramesFromEvent(event); // use for loop so we don't have to reverse whole frames array for (let i = frames.length - 1; i >= 0; i--) { const frame = frames[i];
} return event; } /** JSDoc */ private _getFramesFromEvent(event: Event): StackFrame[] { const exception = event.exception && event.exception.values && event.exception.values[0]; return (exception && exception.stacktrace && exception.stacktrace.frames) || []; } /** JSDoc */ private _getTransaction(frame: StackFrame): string { return frame.module || frame.function ? `${frame.module || '?'}/${frame.function || '?'}` : '<unknown>'; } }
if (frame.in_app === true) { event.transaction = this._getTransaction(frame); break; }
random_line_split
transaction.ts
import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types'; /** Add node transaction to the event */ export class Transaction implements Integration { /** * @inheritDoc */ public name: string = Transaction.id; /** * @inheritDoc */ public static id: string = 'Transaction'; /** * @inheritDoc */ public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void
/** * @inheritDoc */ public process(event: Event): Event { const frames = this._getFramesFromEvent(event); // use for loop so we don't have to reverse whole frames array for (let i = frames.length - 1; i >= 0; i--) { const frame = frames[i]; if (frame.in_app === true) { event.transaction = this._getTransaction(frame); break; } } return event; } /** JSDoc */ private _getFramesFromEvent(event: Event): StackFrame[] { const exception = event.exception && event.exception.values && event.exception.values[0]; return (exception && exception.stacktrace && exception.stacktrace.frames) || []; } /** JSDoc */ private _getTransaction(frame: StackFrame): string { return frame.module || frame.function ? `${frame.module || '?'}/${frame.function || '?'}` : '<unknown>'; } }
{ addGlobalEventProcessor(event => { const self = getCurrentHub().getIntegration(Transaction); if (self) { return self.process(event); } return event; }); }
identifier_body
views.py
from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from .models import Question, Choice def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = { 'latest_question_list': latest_question_list, } return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) # choice = get_object_or_404(Choice, pk=choice_id) # return render(request, 'polls/result.html', {'choice': choice, 'question': question}) return render(request, 'polls/result.html', {'question': question}) def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
random_line_split
views.py
from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from .models import Question, Choice def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = { 'latest_question_list': latest_question_list, } return render(request, 'polls/index.html', context) def
(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) # choice = get_object_or_404(Choice, pk=choice_id) # return render(request, 'polls/result.html', {'choice': choice, 'question': question}) return render(request, 'polls/result.html', {'question': question}) def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
detail
identifier_name
views.py
from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from .models import Question, Choice def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = { 'latest_question_list': latest_question_list, } return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) # choice = get_object_or_404(Choice, pk=choice_id) # return render(request, 'polls/result.html', {'choice': choice, 'question': question}) return render(request, 'polls/result.html', {'question': question}) def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else:
selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
conditional_block
views.py
from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from .models import Question, Choice def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = { 'latest_question_list': latest_question_list, } return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) # choice = get_object_or_404(Choice, pk=choice_id) # return render(request, 'polls/result.html', {'choice': choice, 'question': question}) return render(request, 'polls/result.html', {'question': question}) def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
identifier_body
factory.py
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def mss(**kwargs): # type: (Any) -> MSSBase """ Factory returning a proper MSS class instance. It detects the platform we are running on and chooses the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ # pylint: disable=import-outside-toplevel os_ = platform.system().lower() if os_ == "darwin": from . import darwin return darwin.MSS(**kwargs) if os_ == "linux":
if os_ == "windows": from . import windows return windows.MSS(**kwargs) raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
from . import linux return linux.MSS(**kwargs)
conditional_block
factory.py
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def
(**kwargs): # type: (Any) -> MSSBase """ Factory returning a proper MSS class instance. It detects the platform we are running on and chooses the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ # pylint: disable=import-outside-toplevel os_ = platform.system().lower() if os_ == "darwin": from . import darwin return darwin.MSS(**kwargs) if os_ == "linux": from . import linux return linux.MSS(**kwargs) if os_ == "windows": from . import windows return windows.MSS(**kwargs) raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
mss
identifier_name
factory.py
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def mss(**kwargs): # type: (Any) -> MSSBase
""" Factory returning a proper MSS class instance. It detects the platform we are running on and chooses the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ # pylint: disable=import-outside-toplevel os_ = platform.system().lower() if os_ == "darwin": from . import darwin return darwin.MSS(**kwargs) if os_ == "linux": from . import linux return linux.MSS(**kwargs) if os_ == "windows": from . import windows return windows.MSS(**kwargs) raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
identifier_body
factory.py
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def mss(**kwargs): # type: (Any) -> MSSBase """ Factory returning a proper MSS class instance. It detects the platform we are running on and chooses the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ # pylint: disable=import-outside-toplevel os_ = platform.system().lower() if os_ == "darwin": from . import darwin return darwin.MSS(**kwargs)
return linux.MSS(**kwargs) if os_ == "windows": from . import windows return windows.MSS(**kwargs) raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
if os_ == "linux": from . import linux
random_line_split
hu.js
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image', 'hu', { alertUrl: 'Töltse ki a kép webcímét', alt: 'Buborék szöveg', border: 'Keret', btnUpload: 'Küldés a szerverre', button2Img: 'A kiválasztott képgombból sima képet szeretne csinálni?', hSpace: 'Vízsz. táv', img2Button: 'A kiválasztott képből képgombot szeretne csinálni?', infoTab: 'Alaptulajdonságok', linkTab: 'Hivatkozás', lockRatio: 'Arány megtartása', menu: 'Kép tulajdonságai', resetSize: 'Eredeti méret', title: 'Kép tulajdonságai', titleButton: 'Képgomb tulajdonságai',
vSpace: 'Függ. táv', validateBorder: 'A keret méretének egész számot kell beírni!', validateHSpace: 'Vízszintes távolságnak egész számot kell beírni!', validateVSpace: 'Függőleges távolságnak egész számot kell beírni!' });
upload: 'Feltöltés', urlMissing: 'Hiányzik a kép URL-je',
random_line_split
diagnostic.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use codemap::{Pos, Span}; use codemap; use std::cell::Cell; use std::io; use std::io::stdio::StdWriter; use std::local_data; use extra::term; static BUG_REPORT_URL: &'static str = "https://github.com/mozilla/rust/wiki/HOWTO-submit-a-Rust-bug-report"; pub trait Emitter { fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level); } // a span-handler is like a handler but also // accepts span information for source-location // reporting. pub struct SpanHandler { handler: @Handler, cm: @codemap::CodeMap, } impl SpanHandler { pub fn span_fatal(@self, sp: Span, msg: &str) -> ! { self.handler.emit(Some((&*self.cm, sp)), msg, Fatal); fail!(); } pub fn span_err(@self, sp: Span, msg: &str) { self.handler.emit(Some((&*self.cm, sp)), msg, Error); self.handler.bump_err_count(); } pub fn span_warn(@self, sp: Span, msg: &str) { self.handler.emit(Some((&*self.cm, sp)), msg, Warning); } pub fn span_note(@self, sp: Span, msg: &str) { self.handler.emit(Some((&*self.cm, sp)), msg, Note); } pub fn span_bug(@self, sp: Span, msg: &str) -> ! { self.span_fatal(sp, ice_msg(msg)); } pub fn span_unimpl(@self, sp: Span, msg: &str) -> ! { self.span_bug(sp, ~"unimplemented " + msg); } pub fn handler(@self) -> @Handler { self.handler } } // a handler deals with errors; certain errors // (fatal, bug, unimpl) may cause immediate exit, // others log errors for later reporting. pub struct Handler { err_count: Cell<uint>, emit: @Emitter, } impl Handler { pub fn fatal(@self, msg: &str) -> ! { self.emit.emit(None, msg, Fatal); fail!(); } pub fn err(@self, msg: &str) { self.emit.emit(None, msg, Error); self.bump_err_count(); } pub fn bump_err_count(@self) { self.err_count.set(self.err_count.get() + 1u); } pub fn err_count(@self) -> uint { self.err_count.get() } pub fn has_errors(@self) -> bool { self.err_count.get()> 0u } pub fn abort_if_errors(@self) { let s; match self.err_count.get() { 0u => return, 1u => s = ~"aborting due to previous error", _ => { s = format!("aborting due to {} previous errors", self.err_count.get()); } } self.fatal(s); } pub fn warn(@self, msg: &str) { self.emit.emit(None, msg, Warning); } pub fn note(@self, msg: &str) { self.emit.emit(None, msg, Note); } pub fn bug(@self, msg: &str) -> ! { self.fatal(ice_msg(msg)); } pub fn unimpl(@self, msg: &str) -> ! { self.bug(~"unimplemented " + msg); } pub fn emit(@self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { self.emit.emit(cmsp, msg, lvl); } } pub fn ice_msg(msg: &str) -> ~str { format!("internal compiler error: {}\nThis message reflects a bug in the Rust compiler. \ \nWe would appreciate a bug report: {}", msg, BUG_REPORT_URL) } pub fn mk_span_handler(handler: @Handler, cm: @codemap::CodeMap) -> @SpanHandler { @SpanHandler { handler: handler, cm: cm, } } pub fn mk_handler(emitter: Option<@Emitter>) -> @Handler { let emit: @Emitter = match emitter { Some(e) => e, None => @DefaultEmitter as @Emitter }; @Handler { err_count: Cell::new(0), emit: emit, } } #[deriving(Eq)] pub enum Level { Fatal, Error, Warning, Note, } impl ToStr for Level { fn to_str(&self) -> ~str { match *self { Fatal | Error => ~"error", Warning => ~"warning", Note => ~"note" } } } impl Level { fn color(self) -> term::color::Color { match self { Fatal | Error => term::color::BRIGHT_RED, Warning => term::color::BRIGHT_YELLOW, Note => term::color::BRIGHT_GREEN } } } fn print_maybe_styled(msg: &str, color: term::attr::Attr) { local_data_key!(tls_terminal: ~Option<term::Terminal<StdWriter>>) fn is_stderr_screen() -> bool { use std::libc; unsafe { libc::isatty(libc::STDERR_FILENO) != 0 } } fn write_pretty<T: Writer>(term: &mut term::Terminal<T>, s: &str, c: term::attr::Attr) { term.attr(c); term.write(s.as_bytes()); term.reset(); } if is_stderr_screen() { local_data::get_mut(tls_terminal, |term| { match term { Some(term) => { match **term { Some(ref mut term) => write_pretty(term, msg, color), None => io::stderr().write(msg.as_bytes()) } } None => { let t = ~match term::Terminal::new(io::stderr()) { Ok(mut term) => { write_pretty(&mut term, msg, color); Some(term) } Err(_) => { io::stderr().write(msg.as_bytes()); None } }; local_data::set(tls_terminal, t); } } }); } else { io::stderr().write(msg.as_bytes()); } } fn print_diagnostic(topic: &str, lvl: Level, msg: &str) { let mut stderr = io::stderr(); if !topic.is_empty() { write!(&mut stderr as &mut io::Writer, "{} ", topic); } print_maybe_styled(format!("{}: ", lvl.to_str()), term::attr::ForegroundColor(lvl.color())); print_maybe_styled(format!("{}\n", msg), term::attr::Bold); } pub struct DefaultEmitter; impl Emitter for DefaultEmitter { fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level)
} fn highlight_lines(cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: &codemap::FileLines) { let fm = lines.file; let mut err = io::stderr(); let err = &mut err as &mut io::Writer; // arbitrarily only print up to six lines of the error let max_lines = 6u; let mut elided = false; let mut display_lines = lines.lines.as_slice(); if display_lines.len() > max_lines { display_lines = display_lines.slice(0u, max_lines); elided = true; } // Print the offending lines for line in display_lines.iter() { write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int)); } if elided { let last_line = display_lines[display_lines.len() - 1u]; let s = format!("{}:{} ", fm.name, last_line + 1u); write!(err, "{0:1$}...\n", "", s.len()); } // FIXME (#3260) // If there's one line at fault we can easily point to the problem if lines.lines.len() == 1u { let lo = cm.lookup_char_pos(sp.lo); let mut digits = 0u; let mut num = (lines.lines[0] + 1u) / 10u; // how many digits must be indent past? while num > 0u { num /= 10u; digits += 1u; } // indent past |name:## | and the 0-offset column location let left = fm.name.len() + digits + lo.col.to_uint() + 3u; let mut s = ~""; // Skip is the number of characters we need to skip because they are // part of the 'filename:line ' part of the previous line. let skip = fm.name.len() + digits + 3u; skip.times(|| s.push_char(' ')); let orig = fm.get_line(lines.lines[0] as int); for pos in range(0u, left-skip) { let curChar = (orig[pos] as char); // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). // That way the squiggly line will usually appear in the correct // position. match curChar { '\t' => s.push_char('\t'), _ => s.push_char(' '), }; } write!(err, "{}", s); let mut s = ~"^"; let hi = cm.lookup_char_pos(sp.hi); if hi.col != lo.col { // the ^ already takes up one space let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u; num_squigglies.times(|| s.push_char('~')); } print_maybe_styled(s + "\n", term::attr::ForegroundColor(lvl.color())); } } fn print_macro_backtrace(cm: &codemap::CodeMap, sp: Span) { for ei in sp.expn_info.iter() { let ss = ei.callee.span.as_ref().map_or(~"", |span| cm.span_to_str(*span)); let (pre, post) = match ei.callee.format { codemap::MacroAttribute => ("#[", "]"), codemap::MacroBang => ("", "!") }; print_diagnostic(ss, Note, format!("in expansion of {}{}{}", pre, ei.callee.name, post)); let ss = cm.span_to_str(ei.call_site); print_diagnostic(ss, Note, "expansion site"); print_macro_backtrace(cm, ei.call_site); } } pub fn expect<T:Clone>(diag: @SpanHandler, opt: Option<T>, msg: || -> ~str) -> T { match opt { Some(ref t) => (*t).clone(), None => diag.handler().bug(msg()), } }
{ match cmsp { Some((cm, sp)) => { let sp = cm.adjust_span(sp); let ss = cm.span_to_str(sp); let lines = cm.span_to_lines(sp); print_diagnostic(ss, lvl, msg); highlight_lines(cm, sp, lvl, lines); print_macro_backtrace(cm, sp); } None => print_diagnostic("", lvl, msg), } }
identifier_body
diagnostic.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use codemap::{Pos, Span}; use codemap; use std::cell::Cell; use std::io; use std::io::stdio::StdWriter; use std::local_data; use extra::term; static BUG_REPORT_URL: &'static str = "https://github.com/mozilla/rust/wiki/HOWTO-submit-a-Rust-bug-report"; pub trait Emitter { fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level); } // a span-handler is like a handler but also // accepts span information for source-location // reporting. pub struct SpanHandler { handler: @Handler, cm: @codemap::CodeMap, } impl SpanHandler { pub fn span_fatal(@self, sp: Span, msg: &str) -> ! { self.handler.emit(Some((&*self.cm, sp)), msg, Fatal); fail!(); } pub fn span_err(@self, sp: Span, msg: &str) { self.handler.emit(Some((&*self.cm, sp)), msg, Error); self.handler.bump_err_count(); } pub fn span_warn(@self, sp: Span, msg: &str) { self.handler.emit(Some((&*self.cm, sp)), msg, Warning); } pub fn span_note(@self, sp: Span, msg: &str) { self.handler.emit(Some((&*self.cm, sp)), msg, Note); } pub fn span_bug(@self, sp: Span, msg: &str) -> ! { self.span_fatal(sp, ice_msg(msg)); } pub fn span_unimpl(@self, sp: Span, msg: &str) -> ! { self.span_bug(sp, ~"unimplemented " + msg); } pub fn handler(@self) -> @Handler { self.handler } } // a handler deals with errors; certain errors // (fatal, bug, unimpl) may cause immediate exit, // others log errors for later reporting. pub struct Handler { err_count: Cell<uint>, emit: @Emitter, } impl Handler { pub fn fatal(@self, msg: &str) -> ! { self.emit.emit(None, msg, Fatal); fail!(); } pub fn err(@self, msg: &str) { self.emit.emit(None, msg, Error); self.bump_err_count(); } pub fn bump_err_count(@self) { self.err_count.set(self.err_count.get() + 1u); } pub fn err_count(@self) -> uint { self.err_count.get() } pub fn has_errors(@self) -> bool { self.err_count.get()> 0u } pub fn abort_if_errors(@self) { let s; match self.err_count.get() { 0u => return, 1u => s = ~"aborting due to previous error", _ => { s = format!("aborting due to {} previous errors", self.err_count.get()); } } self.fatal(s); } pub fn warn(@self, msg: &str) { self.emit.emit(None, msg, Warning); } pub fn note(@self, msg: &str) { self.emit.emit(None, msg, Note); } pub fn bug(@self, msg: &str) -> ! { self.fatal(ice_msg(msg)); } pub fn unimpl(@self, msg: &str) -> ! { self.bug(~"unimplemented " + msg); } pub fn emit(@self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { self.emit.emit(cmsp, msg, lvl); } } pub fn ice_msg(msg: &str) -> ~str { format!("internal compiler error: {}\nThis message reflects a bug in the Rust compiler. \ \nWe would appreciate a bug report: {}", msg, BUG_REPORT_URL) } pub fn mk_span_handler(handler: @Handler, cm: @codemap::CodeMap) -> @SpanHandler { @SpanHandler { handler: handler, cm: cm, } } pub fn mk_handler(emitter: Option<@Emitter>) -> @Handler { let emit: @Emitter = match emitter { Some(e) => e, None => @DefaultEmitter as @Emitter }; @Handler { err_count: Cell::new(0), emit: emit, } } #[deriving(Eq)] pub enum Level { Fatal, Error, Warning, Note, } impl ToStr for Level { fn
(&self) -> ~str { match *self { Fatal | Error => ~"error", Warning => ~"warning", Note => ~"note" } } } impl Level { fn color(self) -> term::color::Color { match self { Fatal | Error => term::color::BRIGHT_RED, Warning => term::color::BRIGHT_YELLOW, Note => term::color::BRIGHT_GREEN } } } fn print_maybe_styled(msg: &str, color: term::attr::Attr) { local_data_key!(tls_terminal: ~Option<term::Terminal<StdWriter>>) fn is_stderr_screen() -> bool { use std::libc; unsafe { libc::isatty(libc::STDERR_FILENO) != 0 } } fn write_pretty<T: Writer>(term: &mut term::Terminal<T>, s: &str, c: term::attr::Attr) { term.attr(c); term.write(s.as_bytes()); term.reset(); } if is_stderr_screen() { local_data::get_mut(tls_terminal, |term| { match term { Some(term) => { match **term { Some(ref mut term) => write_pretty(term, msg, color), None => io::stderr().write(msg.as_bytes()) } } None => { let t = ~match term::Terminal::new(io::stderr()) { Ok(mut term) => { write_pretty(&mut term, msg, color); Some(term) } Err(_) => { io::stderr().write(msg.as_bytes()); None } }; local_data::set(tls_terminal, t); } } }); } else { io::stderr().write(msg.as_bytes()); } } fn print_diagnostic(topic: &str, lvl: Level, msg: &str) { let mut stderr = io::stderr(); if !topic.is_empty() { write!(&mut stderr as &mut io::Writer, "{} ", topic); } print_maybe_styled(format!("{}: ", lvl.to_str()), term::attr::ForegroundColor(lvl.color())); print_maybe_styled(format!("{}\n", msg), term::attr::Bold); } pub struct DefaultEmitter; impl Emitter for DefaultEmitter { fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { match cmsp { Some((cm, sp)) => { let sp = cm.adjust_span(sp); let ss = cm.span_to_str(sp); let lines = cm.span_to_lines(sp); print_diagnostic(ss, lvl, msg); highlight_lines(cm, sp, lvl, lines); print_macro_backtrace(cm, sp); } None => print_diagnostic("", lvl, msg), } } } fn highlight_lines(cm: &codemap::CodeMap, sp: Span, lvl: Level, lines: &codemap::FileLines) { let fm = lines.file; let mut err = io::stderr(); let err = &mut err as &mut io::Writer; // arbitrarily only print up to six lines of the error let max_lines = 6u; let mut elided = false; let mut display_lines = lines.lines.as_slice(); if display_lines.len() > max_lines { display_lines = display_lines.slice(0u, max_lines); elided = true; } // Print the offending lines for line in display_lines.iter() { write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int)); } if elided { let last_line = display_lines[display_lines.len() - 1u]; let s = format!("{}:{} ", fm.name, last_line + 1u); write!(err, "{0:1$}...\n", "", s.len()); } // FIXME (#3260) // If there's one line at fault we can easily point to the problem if lines.lines.len() == 1u { let lo = cm.lookup_char_pos(sp.lo); let mut digits = 0u; let mut num = (lines.lines[0] + 1u) / 10u; // how many digits must be indent past? while num > 0u { num /= 10u; digits += 1u; } // indent past |name:## | and the 0-offset column location let left = fm.name.len() + digits + lo.col.to_uint() + 3u; let mut s = ~""; // Skip is the number of characters we need to skip because they are // part of the 'filename:line ' part of the previous line. let skip = fm.name.len() + digits + 3u; skip.times(|| s.push_char(' ')); let orig = fm.get_line(lines.lines[0] as int); for pos in range(0u, left-skip) { let curChar = (orig[pos] as char); // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). // That way the squiggly line will usually appear in the correct // position. match curChar { '\t' => s.push_char('\t'), _ => s.push_char(' '), }; } write!(err, "{}", s); let mut s = ~"^"; let hi = cm.lookup_char_pos(sp.hi); if hi.col != lo.col { // the ^ already takes up one space let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u; num_squigglies.times(|| s.push_char('~')); } print_maybe_styled(s + "\n", term::attr::ForegroundColor(lvl.color())); } } fn print_macro_backtrace(cm: &codemap::CodeMap, sp: Span) { for ei in sp.expn_info.iter() { let ss = ei.callee.span.as_ref().map_or(~"", |span| cm.span_to_str(*span)); let (pre, post) = match ei.callee.format { codemap::MacroAttribute => ("#[", "]"), codemap::MacroBang => ("", "!") }; print_diagnostic(ss, Note, format!("in expansion of {}{}{}", pre, ei.callee.name, post)); let ss = cm.span_to_str(ei.call_site); print_diagnostic(ss, Note, "expansion site"); print_macro_backtrace(cm, ei.call_site); } } pub fn expect<T:Clone>(diag: @SpanHandler, opt: Option<T>, msg: || -> ~str) -> T { match opt { Some(ref t) => (*t).clone(), None => diag.handler().bug(msg()), } }
to_str
identifier_name
diagnostic.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use codemap::{Pos, Span}; use codemap; use std::cell::Cell; use std::io; use std::io::stdio::StdWriter; use std::local_data; use extra::term; static BUG_REPORT_URL: &'static str = "https://github.com/mozilla/rust/wiki/HOWTO-submit-a-Rust-bug-report"; pub trait Emitter { fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level); } // a span-handler is like a handler but also // accepts span information for source-location // reporting. pub struct SpanHandler { handler: @Handler, cm: @codemap::CodeMap, } impl SpanHandler { pub fn span_fatal(@self, sp: Span, msg: &str) -> ! { self.handler.emit(Some((&*self.cm, sp)), msg, Fatal); fail!(); } pub fn span_err(@self, sp: Span, msg: &str) { self.handler.emit(Some((&*self.cm, sp)), msg, Error); self.handler.bump_err_count(); } pub fn span_warn(@self, sp: Span, msg: &str) { self.handler.emit(Some((&*self.cm, sp)), msg, Warning); } pub fn span_note(@self, sp: Span, msg: &str) { self.handler.emit(Some((&*self.cm, sp)), msg, Note); } pub fn span_bug(@self, sp: Span, msg: &str) -> ! { self.span_fatal(sp, ice_msg(msg)); } pub fn span_unimpl(@self, sp: Span, msg: &str) -> ! { self.span_bug(sp, ~"unimplemented " + msg); } pub fn handler(@self) -> @Handler { self.handler } } // a handler deals with errors; certain errors // (fatal, bug, unimpl) may cause immediate exit, // others log errors for later reporting. pub struct Handler { err_count: Cell<uint>, emit: @Emitter, } impl Handler { pub fn fatal(@self, msg: &str) -> ! { self.emit.emit(None, msg, Fatal); fail!(); } pub fn err(@self, msg: &str) { self.emit.emit(None, msg, Error); self.bump_err_count(); } pub fn bump_err_count(@self) { self.err_count.set(self.err_count.get() + 1u); } pub fn err_count(@self) -> uint { self.err_count.get() } pub fn has_errors(@self) -> bool { self.err_count.get()> 0u } pub fn abort_if_errors(@self) { let s; match self.err_count.get() { 0u => return, 1u => s = ~"aborting due to previous error", _ => { s = format!("aborting due to {} previous errors", self.err_count.get()); } } self.fatal(s); } pub fn warn(@self, msg: &str) { self.emit.emit(None, msg, Warning); } pub fn note(@self, msg: &str) { self.emit.emit(None, msg, Note); } pub fn bug(@self, msg: &str) -> ! { self.fatal(ice_msg(msg)); } pub fn unimpl(@self, msg: &str) -> ! { self.bug(~"unimplemented " + msg); } pub fn emit(@self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { self.emit.emit(cmsp, msg, lvl); } } pub fn ice_msg(msg: &str) -> ~str { format!("internal compiler error: {}\nThis message reflects a bug in the Rust compiler. \ \nWe would appreciate a bug report: {}", msg, BUG_REPORT_URL) } pub fn mk_span_handler(handler: @Handler, cm: @codemap::CodeMap) -> @SpanHandler { @SpanHandler { handler: handler, cm: cm, } } pub fn mk_handler(emitter: Option<@Emitter>) -> @Handler { let emit: @Emitter = match emitter { Some(e) => e, None => @DefaultEmitter as @Emitter }; @Handler { err_count: Cell::new(0), emit: emit, } } #[deriving(Eq)] pub enum Level { Fatal, Error, Warning, Note, } impl ToStr for Level { fn to_str(&self) -> ~str { match *self { Fatal | Error => ~"error", Warning => ~"warning", Note => ~"note" } } } impl Level { fn color(self) -> term::color::Color { match self { Fatal | Error => term::color::BRIGHT_RED, Warning => term::color::BRIGHT_YELLOW, Note => term::color::BRIGHT_GREEN } } } fn print_maybe_styled(msg: &str, color: term::attr::Attr) { local_data_key!(tls_terminal: ~Option<term::Terminal<StdWriter>>) fn is_stderr_screen() -> bool { use std::libc; unsafe { libc::isatty(libc::STDERR_FILENO) != 0 } } fn write_pretty<T: Writer>(term: &mut term::Terminal<T>, s: &str, c: term::attr::Attr) { term.attr(c); term.write(s.as_bytes()); term.reset(); } if is_stderr_screen() { local_data::get_mut(tls_terminal, |term| { match term { Some(term) => { match **term { Some(ref mut term) => write_pretty(term, msg, color), None => io::stderr().write(msg.as_bytes()) } } None => { let t = ~match term::Terminal::new(io::stderr()) { Ok(mut term) => { write_pretty(&mut term, msg, color); Some(term) } Err(_) => { io::stderr().write(msg.as_bytes()); None } }; local_data::set(tls_terminal, t); } } }); } else { io::stderr().write(msg.as_bytes()); } } fn print_diagnostic(topic: &str, lvl: Level, msg: &str) { let mut stderr = io::stderr(); if !topic.is_empty() { write!(&mut stderr as &mut io::Writer, "{} ", topic); } print_maybe_styled(format!("{}: ", lvl.to_str()), term::attr::ForegroundColor(lvl.color())); print_maybe_styled(format!("{}\n", msg), term::attr::Bold); } pub struct DefaultEmitter; impl Emitter for DefaultEmitter { fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { match cmsp { Some((cm, sp)) => { let sp = cm.adjust_span(sp); let ss = cm.span_to_str(sp); let lines = cm.span_to_lines(sp); print_diagnostic(ss, lvl, msg); highlight_lines(cm, sp, lvl, lines); print_macro_backtrace(cm, sp); } None => print_diagnostic("", lvl, msg), } } } fn highlight_lines(cm: &codemap::CodeMap, sp: Span, lvl: Level,
// arbitrarily only print up to six lines of the error let max_lines = 6u; let mut elided = false; let mut display_lines = lines.lines.as_slice(); if display_lines.len() > max_lines { display_lines = display_lines.slice(0u, max_lines); elided = true; } // Print the offending lines for line in display_lines.iter() { write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int)); } if elided { let last_line = display_lines[display_lines.len() - 1u]; let s = format!("{}:{} ", fm.name, last_line + 1u); write!(err, "{0:1$}...\n", "", s.len()); } // FIXME (#3260) // If there's one line at fault we can easily point to the problem if lines.lines.len() == 1u { let lo = cm.lookup_char_pos(sp.lo); let mut digits = 0u; let mut num = (lines.lines[0] + 1u) / 10u; // how many digits must be indent past? while num > 0u { num /= 10u; digits += 1u; } // indent past |name:## | and the 0-offset column location let left = fm.name.len() + digits + lo.col.to_uint() + 3u; let mut s = ~""; // Skip is the number of characters we need to skip because they are // part of the 'filename:line ' part of the previous line. let skip = fm.name.len() + digits + 3u; skip.times(|| s.push_char(' ')); let orig = fm.get_line(lines.lines[0] as int); for pos in range(0u, left-skip) { let curChar = (orig[pos] as char); // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). // That way the squiggly line will usually appear in the correct // position. match curChar { '\t' => s.push_char('\t'), _ => s.push_char(' '), }; } write!(err, "{}", s); let mut s = ~"^"; let hi = cm.lookup_char_pos(sp.hi); if hi.col != lo.col { // the ^ already takes up one space let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u; num_squigglies.times(|| s.push_char('~')); } print_maybe_styled(s + "\n", term::attr::ForegroundColor(lvl.color())); } } fn print_macro_backtrace(cm: &codemap::CodeMap, sp: Span) { for ei in sp.expn_info.iter() { let ss = ei.callee.span.as_ref().map_or(~"", |span| cm.span_to_str(*span)); let (pre, post) = match ei.callee.format { codemap::MacroAttribute => ("#[", "]"), codemap::MacroBang => ("", "!") }; print_diagnostic(ss, Note, format!("in expansion of {}{}{}", pre, ei.callee.name, post)); let ss = cm.span_to_str(ei.call_site); print_diagnostic(ss, Note, "expansion site"); print_macro_backtrace(cm, ei.call_site); } } pub fn expect<T:Clone>(diag: @SpanHandler, opt: Option<T>, msg: || -> ~str) -> T { match opt { Some(ref t) => (*t).clone(), None => diag.handler().bug(msg()), } }
lines: &codemap::FileLines) { let fm = lines.file; let mut err = io::stderr(); let err = &mut err as &mut io::Writer;
random_line_split
plshadow.rs
use winapi::*; use create_device; use dxsafe::*; use dxsafe::structwrappers::*; use dxsems::VertexFormat; use std::marker::PhantomData; // Point Light Shadow // The name isn't quite correct. This module just fills depth cubemap. pub struct PLShadow<T: VertexFormat> { pub pso: D3D12PipelineState, pub root_sig: D3D12RootSignature, _luid: Luid, _phd: PhantomData<T>, } impl<T: VertexFormat> PLShadow<T> { pub fn new(dev: &D3D12Device) -> HResult<PLShadow<T>> { let mut vshader_bc = vec![]; let mut gshader_bc = vec![]; let mut pshader_bc = vec![]; let mut rsig_bc = vec![]; trace!("Compiling 'plshadow.hlsl'..."); match create_device::compile_shaders("plshadow.hlsl",&mut[ ("VSMain", "vs_5_0", &mut vshader_bc), ("GSMain", "gs_5_0", &mut gshader_bc), ("PSMain", "ps_5_0", &mut pshader_bc), ("RSD", "rootsig_1_0", &mut rsig_bc),
Ok(_) => {}, }; trace!("Done"); trace!("Root signature creation"); let root_sig = try!(dev.create_root_signature(0, &rsig_bc[..])); try!(root_sig.set_name("plshadow RSD")); let input_elts_desc = T::generate(0); // pso_desc contains pointers to local data, so I mustn't pass it around, but I can. Unsafe. let pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { pRootSignature: root_sig.iptr() as *mut _, VS: ShaderBytecode::from_vec(&vshader_bc).get(), GS: ShaderBytecode::from_vec(&gshader_bc).get(), PS: ShaderBytecode::from_vec(&pshader_bc).get(), RasterizerState: D3D12_RASTERIZER_DESC { CullMode: D3D12_CULL_MODE_NONE, DepthBias: 550, SlopeScaledDepthBias: 1.5, ..rasterizer_desc_default() }, InputLayout: D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: input_elts_desc.as_ptr(), NumElements: input_elts_desc.len() as u32, }, PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, NumRenderTargets: 0, // Pixel shader writes depth buffer only DSVFormat: DXGI_FORMAT_D32_FLOAT, Flags: D3D12_PIPELINE_STATE_FLAG_NONE, // Take other fields from default gpsd ..graphics_pipeline_state_desc_default() }; //pso_desc.RTVFormats[0] = DXGI_FORMAT_D32_FLOAT; trace!("Graphics pipeline state creation"); let pso = try!(dev.create_graphics_pipeline_state(&pso_desc)); Ok(PLShadow::<T> { pso: pso, root_sig: root_sig, _luid: Luid(dev.get_adapter_luid()), _phd: PhantomData, }) } }
], D3DCOMPILE_OPTIMIZATION_LEVEL3) { Err(err) => { error!("Error compiling 'plshadow.hlsl': {}", err); return Err(E_FAIL); },
random_line_split
plshadow.rs
use winapi::*; use create_device; use dxsafe::*; use dxsafe::structwrappers::*; use dxsems::VertexFormat; use std::marker::PhantomData; // Point Light Shadow // The name isn't quite correct. This module just fills depth cubemap. pub struct PLShadow<T: VertexFormat> { pub pso: D3D12PipelineState, pub root_sig: D3D12RootSignature, _luid: Luid, _phd: PhantomData<T>, } impl<T: VertexFormat> PLShadow<T> { pub fn
(dev: &D3D12Device) -> HResult<PLShadow<T>> { let mut vshader_bc = vec![]; let mut gshader_bc = vec![]; let mut pshader_bc = vec![]; let mut rsig_bc = vec![]; trace!("Compiling 'plshadow.hlsl'..."); match create_device::compile_shaders("plshadow.hlsl",&mut[ ("VSMain", "vs_5_0", &mut vshader_bc), ("GSMain", "gs_5_0", &mut gshader_bc), ("PSMain", "ps_5_0", &mut pshader_bc), ("RSD", "rootsig_1_0", &mut rsig_bc), ], D3DCOMPILE_OPTIMIZATION_LEVEL3) { Err(err) => { error!("Error compiling 'plshadow.hlsl': {}", err); return Err(E_FAIL); }, Ok(_) => {}, }; trace!("Done"); trace!("Root signature creation"); let root_sig = try!(dev.create_root_signature(0, &rsig_bc[..])); try!(root_sig.set_name("plshadow RSD")); let input_elts_desc = T::generate(0); // pso_desc contains pointers to local data, so I mustn't pass it around, but I can. Unsafe. let pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { pRootSignature: root_sig.iptr() as *mut _, VS: ShaderBytecode::from_vec(&vshader_bc).get(), GS: ShaderBytecode::from_vec(&gshader_bc).get(), PS: ShaderBytecode::from_vec(&pshader_bc).get(), RasterizerState: D3D12_RASTERIZER_DESC { CullMode: D3D12_CULL_MODE_NONE, DepthBias: 550, SlopeScaledDepthBias: 1.5, ..rasterizer_desc_default() }, InputLayout: D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: input_elts_desc.as_ptr(), NumElements: input_elts_desc.len() as u32, }, PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, NumRenderTargets: 0, // Pixel shader writes depth buffer only DSVFormat: DXGI_FORMAT_D32_FLOAT, Flags: D3D12_PIPELINE_STATE_FLAG_NONE, // Take other fields from default gpsd ..graphics_pipeline_state_desc_default() }; //pso_desc.RTVFormats[0] = DXGI_FORMAT_D32_FLOAT; trace!("Graphics pipeline state creation"); let pso = try!(dev.create_graphics_pipeline_state(&pso_desc)); Ok(PLShadow::<T> { pso: pso, root_sig: root_sig, _luid: Luid(dev.get_adapter_luid()), _phd: PhantomData, }) } }
new
identifier_name
plshadow.rs
use winapi::*; use create_device; use dxsafe::*; use dxsafe::structwrappers::*; use dxsems::VertexFormat; use std::marker::PhantomData; // Point Light Shadow // The name isn't quite correct. This module just fills depth cubemap. pub struct PLShadow<T: VertexFormat> { pub pso: D3D12PipelineState, pub root_sig: D3D12RootSignature, _luid: Luid, _phd: PhantomData<T>, } impl<T: VertexFormat> PLShadow<T> { pub fn new(dev: &D3D12Device) -> HResult<PLShadow<T>>
}
{ let mut vshader_bc = vec![]; let mut gshader_bc = vec![]; let mut pshader_bc = vec![]; let mut rsig_bc = vec![]; trace!("Compiling 'plshadow.hlsl'..."); match create_device::compile_shaders("plshadow.hlsl",&mut[ ("VSMain", "vs_5_0", &mut vshader_bc), ("GSMain", "gs_5_0", &mut gshader_bc), ("PSMain", "ps_5_0", &mut pshader_bc), ("RSD", "rootsig_1_0", &mut rsig_bc), ], D3DCOMPILE_OPTIMIZATION_LEVEL3) { Err(err) => { error!("Error compiling 'plshadow.hlsl': {}", err); return Err(E_FAIL); }, Ok(_) => {}, }; trace!("Done"); trace!("Root signature creation"); let root_sig = try!(dev.create_root_signature(0, &rsig_bc[..])); try!(root_sig.set_name("plshadow RSD")); let input_elts_desc = T::generate(0); // pso_desc contains pointers to local data, so I mustn't pass it around, but I can. Unsafe. let pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { pRootSignature: root_sig.iptr() as *mut _, VS: ShaderBytecode::from_vec(&vshader_bc).get(), GS: ShaderBytecode::from_vec(&gshader_bc).get(), PS: ShaderBytecode::from_vec(&pshader_bc).get(), RasterizerState: D3D12_RASTERIZER_DESC { CullMode: D3D12_CULL_MODE_NONE, DepthBias: 550, SlopeScaledDepthBias: 1.5, ..rasterizer_desc_default() }, InputLayout: D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: input_elts_desc.as_ptr(), NumElements: input_elts_desc.len() as u32, }, PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, NumRenderTargets: 0, // Pixel shader writes depth buffer only DSVFormat: DXGI_FORMAT_D32_FLOAT, Flags: D3D12_PIPELINE_STATE_FLAG_NONE, // Take other fields from default gpsd ..graphics_pipeline_state_desc_default() }; //pso_desc.RTVFormats[0] = DXGI_FORMAT_D32_FLOAT; trace!("Graphics pipeline state creation"); let pso = try!(dev.create_graphics_pipeline_state(&pso_desc)); Ok(PLShadow::<T> { pso: pso, root_sig: root_sig, _luid: Luid(dev.get_adapter_luid()), _phd: PhantomData, }) }
identifier_body
lib.rs
pub mod nodes; pub mod parser; pub mod tokenizer; mod tests; use tokenizer::*; use parser::*; use nodes::*; pub struct Document { root: Element, } impl Document { pub fn new() -> Document { Document { root: Element::new("root"), } } pub fn from_element(e: Element) -> Document { Document { root: e, } } pub fn from_string(s: &str) -> Result<Document, String> { let tokens = match tokenize(&s) { Ok(tokens) => tokens, Err(e) => return Err(e), }; let element = match parse(tokens) { Ok(element) => element, Err(e) => return Err(e), }; Ok(Document::from_element(element)) } pub fn from_file(p: &str) -> Result<Document, String> { let string = match string_from_file(p) { Some(string) => string, None => return Err("Couldn't make String from file".into()), }; match Document::from_string(&string) { Ok(document) => Ok(document), Err(e) => Err(e), } } pub fn
(&self) -> &Element { match self.root.get_first_child() { Some(c) => c, None => panic!("Document has no root element!"), } } pub fn print(&self) { self.root.print(0); } }
get_root
identifier_name
lib.rs
pub mod nodes; pub mod parser; pub mod tokenizer;
mod tests; use tokenizer::*; use parser::*; use nodes::*; pub struct Document { root: Element, } impl Document { pub fn new() -> Document { Document { root: Element::new("root"), } } pub fn from_element(e: Element) -> Document { Document { root: e, } } pub fn from_string(s: &str) -> Result<Document, String> { let tokens = match tokenize(&s) { Ok(tokens) => tokens, Err(e) => return Err(e), }; let element = match parse(tokens) { Ok(element) => element, Err(e) => return Err(e), }; Ok(Document::from_element(element)) } pub fn from_file(p: &str) -> Result<Document, String> { let string = match string_from_file(p) { Some(string) => string, None => return Err("Couldn't make String from file".into()), }; match Document::from_string(&string) { Ok(document) => Ok(document), Err(e) => Err(e), } } pub fn get_root(&self) -> &Element { match self.root.get_first_child() { Some(c) => c, None => panic!("Document has no root element!"), } } pub fn print(&self) { self.root.print(0); } }
random_line_split
lib.rs
pub mod nodes; pub mod parser; pub mod tokenizer; mod tests; use tokenizer::*; use parser::*; use nodes::*; pub struct Document { root: Element, } impl Document { pub fn new() -> Document { Document { root: Element::new("root"), } } pub fn from_element(e: Element) -> Document
pub fn from_string(s: &str) -> Result<Document, String> { let tokens = match tokenize(&s) { Ok(tokens) => tokens, Err(e) => return Err(e), }; let element = match parse(tokens) { Ok(element) => element, Err(e) => return Err(e), }; Ok(Document::from_element(element)) } pub fn from_file(p: &str) -> Result<Document, String> { let string = match string_from_file(p) { Some(string) => string, None => return Err("Couldn't make String from file".into()), }; match Document::from_string(&string) { Ok(document) => Ok(document), Err(e) => Err(e), } } pub fn get_root(&self) -> &Element { match self.root.get_first_child() { Some(c) => c, None => panic!("Document has no root element!"), } } pub fn print(&self) { self.root.print(0); } }
{ Document { root: e, } }
identifier_body
file.rs
//! Provides File Management functions use std::ffi; use std::os::windows::ffi::{ OsStrExt, OsStringExt }; use std::default; use std::ptr; use std::mem; use std::convert; use std::io; use crate::inner_raw as raw; use self::raw::winapi::*; use crate::utils; const NO_MORE_FILES: i32 = ERROR_NO_MORE_FILES as i32; ///Level of information to store about file during search. pub enum FileInfoLevel { ///Corresponds to FindExInfoStandard. Default. Standard, ///Corresponds to FindExInfoBasic. Basic, ///Corresponds to FindExInfoMaxInfoLevel. Max } impl convert::Into<FINDEX_INFO_LEVELS> for FileInfoLevel { fn into(self) -> FINDEX_INFO_LEVELS { match self { FileInfoLevel::Standard => FindExInfoStandard, FileInfoLevel::Basic => FindExInfoBasic, FileInfoLevel::Max => FindExInfoMaxInfoLevel } } } impl default::Default for FileInfoLevel { fn default() -> Self { FileInfoLevel::Standard } } ///File search type pub enum FileSearchType { ///Search file by name. Corresponds to FindExSearchNameMatch. Default. NameMatch, ///Ask to search directories only. Corresponds to FindExSearchLimitToDirectories. /// ///Note that this flag may be ignored by OS. DirectoriesOnly } impl convert::Into<FINDEX_SEARCH_OPS> for FileSearchType { fn into(self) -> FINDEX_SEARCH_OPS { match self { FileSearchType::NameMatch => FindExSearchNameMatch, FileSearchType::DirectoriesOnly => FindExSearchLimitToDirectories } } } impl default::Default for FileSearchType { fn default() -> Self { FileSearchType::NameMatch } } ///File System Entry. pub struct Entry(WIN32_FIND_DATAW); impl Entry { ///Determines whether Entry is directory or not. pub fn is_dir(&self) -> bool { (self.0.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 } ///Determines whether Entry is file or not. pub fn is_file(&self) -> bool { !self.is_dir() } ///Returns size of entry pub fn size(&self) -> u64
///Returns whether Entry is read-only pub fn is_read_only(&self) -> bool { (self.0.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0 } ///Returns name of Entry. pub fn name(&self) -> ffi::OsString { ffi::OsString::from_wide(match self.0.cFileName.iter().position(|c| *c == 0) { Some(n) => &self.0.cFileName[..n], None => &self.0.cFileName }) } } ///File System Search iterator. pub struct Search(HANDLE); impl Search { ///Creates new instance of Search. /// ///Due to the way how underlying WinAPI works first entry is also returned alongside it. pub fn new<T: ?Sized + AsRef<ffi::OsStr>>(name: &T, level: FileInfoLevel, typ: FileSearchType, flags: DWORD) -> io::Result<(Search, Entry)> { let mut utf16_buff: Vec<u16> = name.as_ref().encode_wide().collect(); utf16_buff.push(0); let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() }; let result = unsafe { FindFirstFileExW(utf16_buff.as_ptr(), level.into(), &mut file_data as *mut _ as *mut c_void, typ.into(), ptr::null_mut(), flags) }; if result == INVALID_HANDLE_VALUE { Err(utils::get_last_error()) } else { Ok((Search(result), Entry(file_data))) } } ///Attempts to search again. pub fn again(&self) -> io::Result<Entry> { let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() }; unsafe { if FindNextFileW(self.0, &mut file_data) != 0 { Ok(Entry(file_data)) } else { Err(utils::get_last_error()) } } } ///Closes search. pub fn close(self) { drop(self.0); } } impl Iterator for Search { type Item = io::Result<Entry>; fn next(&mut self) -> Option<Self::Item> { match self.again() { Ok(data) => Some(Ok(data)), Err(error) => { match error.raw_os_error() { Some(NO_MORE_FILES) => None, _ => Some(Err(error)) } } } } } impl Drop for Search { fn drop(&mut self) { unsafe { debug_assert!(FindClose(self.0) != 0); } } }
{ ((self.0.nFileSizeHigh as u64) << 32) | (self.0.nFileSizeLow as u64) }
identifier_body
file.rs
//! Provides File Management functions use std::ffi; use std::os::windows::ffi::{ OsStrExt, OsStringExt }; use std::default; use std::ptr; use std::mem; use std::convert; use std::io; use crate::inner_raw as raw; use self::raw::winapi::*; use crate::utils; const NO_MORE_FILES: i32 = ERROR_NO_MORE_FILES as i32; ///Level of information to store about file during search. pub enum FileInfoLevel { ///Corresponds to FindExInfoStandard. Default. Standard, ///Corresponds to FindExInfoBasic. Basic, ///Corresponds to FindExInfoMaxInfoLevel. Max } impl convert::Into<FINDEX_INFO_LEVELS> for FileInfoLevel { fn into(self) -> FINDEX_INFO_LEVELS { match self { FileInfoLevel::Standard => FindExInfoStandard, FileInfoLevel::Basic => FindExInfoBasic, FileInfoLevel::Max => FindExInfoMaxInfoLevel } } } impl default::Default for FileInfoLevel { fn default() -> Self { FileInfoLevel::Standard } } ///File search type pub enum FileSearchType { ///Search file by name. Corresponds to FindExSearchNameMatch. Default. NameMatch, ///Ask to search directories only. Corresponds to FindExSearchLimitToDirectories. /// ///Note that this flag may be ignored by OS. DirectoriesOnly } impl convert::Into<FINDEX_SEARCH_OPS> for FileSearchType { fn into(self) -> FINDEX_SEARCH_OPS { match self { FileSearchType::NameMatch => FindExSearchNameMatch, FileSearchType::DirectoriesOnly => FindExSearchLimitToDirectories } } } impl default::Default for FileSearchType { fn default() -> Self { FileSearchType::NameMatch } } ///File System Entry. pub struct Entry(WIN32_FIND_DATAW); impl Entry { ///Determines whether Entry is directory or not. pub fn is_dir(&self) -> bool { (self.0.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 } ///Determines whether Entry is file or not. pub fn is_file(&self) -> bool { !self.is_dir() } ///Returns size of entry pub fn
(&self) -> u64 { ((self.0.nFileSizeHigh as u64) << 32) | (self.0.nFileSizeLow as u64) } ///Returns whether Entry is read-only pub fn is_read_only(&self) -> bool { (self.0.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0 } ///Returns name of Entry. pub fn name(&self) -> ffi::OsString { ffi::OsString::from_wide(match self.0.cFileName.iter().position(|c| *c == 0) { Some(n) => &self.0.cFileName[..n], None => &self.0.cFileName }) } } ///File System Search iterator. pub struct Search(HANDLE); impl Search { ///Creates new instance of Search. /// ///Due to the way how underlying WinAPI works first entry is also returned alongside it. pub fn new<T: ?Sized + AsRef<ffi::OsStr>>(name: &T, level: FileInfoLevel, typ: FileSearchType, flags: DWORD) -> io::Result<(Search, Entry)> { let mut utf16_buff: Vec<u16> = name.as_ref().encode_wide().collect(); utf16_buff.push(0); let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() }; let result = unsafe { FindFirstFileExW(utf16_buff.as_ptr(), level.into(), &mut file_data as *mut _ as *mut c_void, typ.into(), ptr::null_mut(), flags) }; if result == INVALID_HANDLE_VALUE { Err(utils::get_last_error()) } else { Ok((Search(result), Entry(file_data))) } } ///Attempts to search again. pub fn again(&self) -> io::Result<Entry> { let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() }; unsafe { if FindNextFileW(self.0, &mut file_data) != 0 { Ok(Entry(file_data)) } else { Err(utils::get_last_error()) } } } ///Closes search. pub fn close(self) { drop(self.0); } } impl Iterator for Search { type Item = io::Result<Entry>; fn next(&mut self) -> Option<Self::Item> { match self.again() { Ok(data) => Some(Ok(data)), Err(error) => { match error.raw_os_error() { Some(NO_MORE_FILES) => None, _ => Some(Err(error)) } } } } } impl Drop for Search { fn drop(&mut self) { unsafe { debug_assert!(FindClose(self.0) != 0); } } }
size
identifier_name
file.rs
//! Provides File Management functions use std::ffi; use std::os::windows::ffi::{ OsStrExt, OsStringExt }; use std::default; use std::ptr; use std::mem; use std::convert; use std::io; use crate::inner_raw as raw; use self::raw::winapi::*; use crate::utils; const NO_MORE_FILES: i32 = ERROR_NO_MORE_FILES as i32; ///Level of information to store about file during search. pub enum FileInfoLevel { ///Corresponds to FindExInfoStandard. Default. Standard, ///Corresponds to FindExInfoBasic. Basic, ///Corresponds to FindExInfoMaxInfoLevel. Max } impl convert::Into<FINDEX_INFO_LEVELS> for FileInfoLevel { fn into(self) -> FINDEX_INFO_LEVELS { match self { FileInfoLevel::Standard => FindExInfoStandard, FileInfoLevel::Basic => FindExInfoBasic, FileInfoLevel::Max => FindExInfoMaxInfoLevel } } } impl default::Default for FileInfoLevel { fn default() -> Self { FileInfoLevel::Standard } } ///File search type pub enum FileSearchType { ///Search file by name. Corresponds to FindExSearchNameMatch. Default. NameMatch, ///Ask to search directories only. Corresponds to FindExSearchLimitToDirectories. /// ///Note that this flag may be ignored by OS. DirectoriesOnly } impl convert::Into<FINDEX_SEARCH_OPS> for FileSearchType { fn into(self) -> FINDEX_SEARCH_OPS { match self { FileSearchType::NameMatch => FindExSearchNameMatch, FileSearchType::DirectoriesOnly => FindExSearchLimitToDirectories } } } impl default::Default for FileSearchType { fn default() -> Self { FileSearchType::NameMatch } } ///File System Entry. pub struct Entry(WIN32_FIND_DATAW); impl Entry { ///Determines whether Entry is directory or not. pub fn is_dir(&self) -> bool { (self.0.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 } ///Determines whether Entry is file or not. pub fn is_file(&self) -> bool {
!self.is_dir() } ///Returns size of entry pub fn size(&self) -> u64 { ((self.0.nFileSizeHigh as u64) << 32) | (self.0.nFileSizeLow as u64) } ///Returns whether Entry is read-only pub fn is_read_only(&self) -> bool { (self.0.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0 } ///Returns name of Entry. pub fn name(&self) -> ffi::OsString { ffi::OsString::from_wide(match self.0.cFileName.iter().position(|c| *c == 0) { Some(n) => &self.0.cFileName[..n], None => &self.0.cFileName }) } } ///File System Search iterator. pub struct Search(HANDLE); impl Search { ///Creates new instance of Search. /// ///Due to the way how underlying WinAPI works first entry is also returned alongside it. pub fn new<T: ?Sized + AsRef<ffi::OsStr>>(name: &T, level: FileInfoLevel, typ: FileSearchType, flags: DWORD) -> io::Result<(Search, Entry)> { let mut utf16_buff: Vec<u16> = name.as_ref().encode_wide().collect(); utf16_buff.push(0); let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() }; let result = unsafe { FindFirstFileExW(utf16_buff.as_ptr(), level.into(), &mut file_data as *mut _ as *mut c_void, typ.into(), ptr::null_mut(), flags) }; if result == INVALID_HANDLE_VALUE { Err(utils::get_last_error()) } else { Ok((Search(result), Entry(file_data))) } } ///Attempts to search again. pub fn again(&self) -> io::Result<Entry> { let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() }; unsafe { if FindNextFileW(self.0, &mut file_data) != 0 { Ok(Entry(file_data)) } else { Err(utils::get_last_error()) } } } ///Closes search. pub fn close(self) { drop(self.0); } } impl Iterator for Search { type Item = io::Result<Entry>; fn next(&mut self) -> Option<Self::Item> { match self.again() { Ok(data) => Some(Ok(data)), Err(error) => { match error.raw_os_error() { Some(NO_MORE_FILES) => None, _ => Some(Err(error)) } } } } } impl Drop for Search { fn drop(&mut self) { unsafe { debug_assert!(FindClose(self.0) != 0); } } }
random_line_split
mut_dns_packet.rs
use buf::*; #[derive(Debug)] pub struct MutDnsPacket<'a> { buf: &'a mut [u8], pos: usize, } impl<'a> MutDnsPacket<'a> { pub fn new(buf: &mut [u8]) -> MutDnsPacket { MutDnsPacket::new_at(buf, 0) } pub fn new_at(buf: &mut [u8], pos: usize) -> MutDnsPacket { debug!("New MutDnsPacket. buf.len()= {:?}", buf.len()); MutDnsPacket { buf: buf, pos: pos, } } } impl<'a> BufWrite for MutDnsPacket<'a> { fn buf(&mut self) -> &mut [u8] { self.buf } } impl<'a> BufRead for MutDnsPacket<'a> { fn buf(&self) -> &[u8] { self.buf } } impl<'a> DirectAccessBuf for MutDnsPacket<'a> { fn pos(&self) -> usize { self.pos } fn set_pos(&mut self, pos: usize) { self.pos = pos; } fn len(&self) -> usize { self.buf().len() } } ///Iterate each 16bit word in the packet impl<'a> Iterator for MutDnsPacket<'a> { ///2 octets of data and the position type Item = (u16, usize); /// ///Returns two octets in the order they expressed in the spec. I.e. first byte shifted to the left /// fn next(&mut self) -> Option<Self::Item> { self.next_u16().and_then(|n| Some((n, self.pos))) } } #[cfg(test)] mod tests { use super::MutDnsPacket; use buf::*; fn test_buf() -> Vec<u8> { // // 00001000 01110001 00000001 00000000 00000000 00000001 00000000 00000000 00000000 // 00000000 00000000 00000000 00000101 01111001 01100001 01101000 01101111 01101111 // 00000011 01100011 01101111 01101101 00000000 00000000 00000001 00000000 00000001 // return vec![8, 113, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 5, 121, 97, 104, 111, 111, 3, 99, 111, 109, 0, 0, 1, 0, 1]; } #[test] fn write_u8() { let mut buf = test_buf(); let mut slice = buf.as_mut_slice(); let mut packet = MutDnsPacket::new(&mut slice); packet.write_u8(7); packet.write_u8(8); packet.write_u8(9); packet.seek(0); assert_eq!(7, packet.next_u8().unwrap()); assert_eq!(8, packet.next_u8().unwrap()); assert_eq!(9, packet.next_u8().unwrap()); } #[test] fn write_u16()
#[test] fn write_u16_bounds() { let mut vec = vec![0, 0, 0, 0]; let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); assert_eq!(true, packet.write_u16(1)); assert_eq!(true, packet.write_u16(1)); assert_eq!(false, packet.write_u16(1)); //no room println!("{:?}", packet); } #[test] fn write_u32() { let mut vec = vec![0, 0, 0, 0]; let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); assert_eq!(true, packet.write_u32(123456789)); println!("{:?}", packet); packet.seek(0); assert_eq!(123456789, packet.next_u32().unwrap()); } }
{ let mut vec = test_buf(); let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); packet.write_u16(2161); packet.write_u16(1); packet.seek(0); println!("{:?}", packet); assert_eq!(2161, packet.next_u16().unwrap()); assert_eq!(1, packet.next_u16().unwrap()); }
identifier_body
mut_dns_packet.rs
use buf::*; #[derive(Debug)] pub struct MutDnsPacket<'a> { buf: &'a mut [u8], pos: usize, } impl<'a> MutDnsPacket<'a> { pub fn new(buf: &mut [u8]) -> MutDnsPacket { MutDnsPacket::new_at(buf, 0) } pub fn new_at(buf: &mut [u8], pos: usize) -> MutDnsPacket { debug!("New MutDnsPacket. buf.len()= {:?}", buf.len()); MutDnsPacket { buf: buf, pos: pos, } } } impl<'a> BufWrite for MutDnsPacket<'a> { fn buf(&mut self) -> &mut [u8] { self.buf } } impl<'a> BufRead for MutDnsPacket<'a> { fn buf(&self) -> &[u8] { self.buf } } impl<'a> DirectAccessBuf for MutDnsPacket<'a> { fn pos(&self) -> usize { self.pos } fn set_pos(&mut self, pos: usize) { self.pos = pos; } fn len(&self) -> usize { self.buf().len() } } ///Iterate each 16bit word in the packet impl<'a> Iterator for MutDnsPacket<'a> { ///2 octets of data and the position type Item = (u16, usize); /// ///Returns two octets in the order they expressed in the spec. I.e. first byte shifted to the left /// fn next(&mut self) -> Option<Self::Item> { self.next_u16().and_then(|n| Some((n, self.pos))) } } #[cfg(test)] mod tests { use super::MutDnsPacket; use buf::*; fn test_buf() -> Vec<u8> { // // 00001000 01110001 00000001 00000000 00000000 00000001 00000000 00000000 00000000 // 00000000 00000000 00000000 00000101 01111001 01100001 01101000 01101111 01101111 // 00000011 01100011 01101111 01101101 00000000 00000000 00000001 00000000 00000001 // return vec![8, 113, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 5, 121, 97, 104, 111, 111, 3, 99, 111, 109, 0, 0, 1, 0, 1]; } #[test] fn write_u8() { let mut buf = test_buf(); let mut slice = buf.as_mut_slice(); let mut packet = MutDnsPacket::new(&mut slice); packet.write_u8(7); packet.write_u8(8); packet.write_u8(9); packet.seek(0); assert_eq!(7, packet.next_u8().unwrap());
#[test] fn write_u16() { let mut vec = test_buf(); let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); packet.write_u16(2161); packet.write_u16(1); packet.seek(0); println!("{:?}", packet); assert_eq!(2161, packet.next_u16().unwrap()); assert_eq!(1, packet.next_u16().unwrap()); } #[test] fn write_u16_bounds() { let mut vec = vec![0, 0, 0, 0]; let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); assert_eq!(true, packet.write_u16(1)); assert_eq!(true, packet.write_u16(1)); assert_eq!(false, packet.write_u16(1)); //no room println!("{:?}", packet); } #[test] fn write_u32() { let mut vec = vec![0, 0, 0, 0]; let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); assert_eq!(true, packet.write_u32(123456789)); println!("{:?}", packet); packet.seek(0); assert_eq!(123456789, packet.next_u32().unwrap()); } }
assert_eq!(8, packet.next_u8().unwrap()); assert_eq!(9, packet.next_u8().unwrap()); }
random_line_split