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
tile_coding.py
# -*- coding: utf8 -*- from typing import List, Tuple import numpy as np from yarll.functionapproximation.function_approximator import FunctionApproximator class TileCoding(FunctionApproximator): """Map states to tiles""" def __init__(self, x_low, x_high, y_low, y_high, n_tilings: int, n_y_tiles: int, n_x_ti...
self.features_shape = (self.n_tilings, self.n_y_tiles, self.n_x_tiles, self.n_actions) self.thetas = np.random.uniform(size=self.features_shape) # Initialise randomly with values between 0 and 1 def summed_thetas(self, state, action): """Theta values for features present for state and ac...
self.tile_starts.append(( self.x_low + np.random.rand() * self.tile_width, self.y_low + np.random.rand() * self.tile_height))
conditional_block
tile_coding.py
# -*- coding: utf8 -*- from typing import List, Tuple import numpy as np from yarll.functionapproximation.function_approximator import FunctionApproximator class TileCoding(FunctionApproximator): """Map states to tiles""" def __init__(self, x_low, x_high, y_low, y_high, n_tilings: int, n_y_tiles: int, n_x_ti...
def present_features(self, state, action): """Features that are active for the given state and action.""" result = np.zeros(self.thetas.shape) # By default, all of them are inactve for i in range(self.n_tilings): shifted = state - self.tile_starts[i] x, y = shifted ...
return summed
random_line_split
tile_coding.py
# -*- coding: utf8 -*- from typing import List, Tuple import numpy as np from yarll.functionapproximation.function_approximator import FunctionApproximator class TileCoding(FunctionApproximator):
"""Map states to tiles""" def __init__(self, x_low, x_high, y_low, y_high, n_tilings: int, n_y_tiles: int, n_x_tiles: int, n_actions: int) -> None: super(TileCoding, self).__init__(n_actions) self.x_low = x_low self.x_high = x_high self.y_low = y_low self.y_high = y_high ...
identifier_body
lexer.rs
pub type Spanned<Tok, Loc, Error> = Result<(Loc, Tok, Loc), Error>; #[derive(Debug)] pub enum Tok { Space, Tab, Linefeed, } #[derive(Debug)] pub enum LexicalError { // Not possible } use std::str::CharIndices; pub struct
<'input> { chars: CharIndices<'input>, } impl<'input> Lexer<'input> { pub fn new(input: &'input str) -> Self { Lexer { chars: input.char_indices() } } } impl<'input> Iterator for Lexer<'input> { type Item = Spanned<Tok, usize, LexicalError>; fn next(&mut self) -> Option<Self::Item> { ...
Lexer
identifier_name
lexer.rs
pub type Spanned<Tok, Loc, Error> = Result<(Loc, Tok, Loc), Error>; #[derive(Debug)] pub enum Tok { Space, Tab, Linefeed, } #[derive(Debug)] pub enum LexicalError { // Not possible } use std::str::CharIndices; pub struct Lexer<'input> { chars: CharIndices<'input>, } impl<'input> Lexer<'input> {...
} } impl<'input> Iterator for Lexer<'input> { type Item = Spanned<Tok, usize, LexicalError>; fn next(&mut self) -> Option<Self::Item> { loop { match self.chars.next() { Some((i, ' ')) => return Some(Ok((i, Tok::Space, i+1))), Some((i, '\t')) => return So...
Lexer { chars: input.char_indices() }
random_line_split
issueView.js
// This view renders a single issue, which contains sub-views for the reporter, labels, truncated summary, etc. var IssueView = Backbone.View.extend({ className: 'issuelist-item-view', render: function() { // Append labels to this view. var labels = this.model.get('labels'); var labelView = new Labe...
return this; } });
{ var shortSummaryModel = new ShortSummaryModel({ text: summaryText }); var shortSummaryView = new ShortSummaryView({ model: shortSummaryModel }); this.$el.append(shortSummaryView.render().$el); }
conditional_block
issueView.js
// This view renders a single issue, which contains sub-views for the reporter, labels, truncated summary, etc. var IssueView = Backbone.View.extend({ className: 'issuelist-item-view',
render: function() { // Append labels to this view. var labels = this.model.get('labels'); var labelView = new LabelView(labels); this.$el.append(labelView.render().$el); // Append the issue title and number to this view. var issueMetaInfoView = new IssueMetaInfoView({ title: this.model.get('...
random_line_split
constants.py
# Copyright 2019 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, ...
'tooltip': 'Feature indicating the priority of this issue.' }, { 'name': 'examples', 'title': 'Log examples', 'tooltip': 'Sample logs showing this issue.' }, { 'name': 'solutions', 'title': 'Recommended solutions', 'tooltip': 'Possible solutions to...
{ 'name': 'score', 'title': 'Priority score (experimental)',
random_line_split
clothes_shop.py
clouthes = ["T-Shirt","Sweater"] print("Hello, welcome to my shop\n") while (True): comment = input("Welcome to our shop, what do you want (C, R, U, D)? ") if comment.upper()=="C": new_item = input("Enter new item: ") clouthes.append(new_item.capitalize()) elif comment.upper()=="R": print(end='') elif comment...
print("Sorry, your item is out of sale!") else: print("Allahu akbar! We're in reconstructing and can't serve you. See you again!") # items =[", "+clouthe for clouthe in clouthes if clouthes.index(clouthe)>0] # items.insert(0,clouthes[0]) # print("Our items: {0}".format(items)) # print("\n") print("Our items...
random_line_split
clothes_shop.py
clouthes = ["T-Shirt","Sweater"] print("Hello, welcome to my shop\n") while (True): comment = input("Welcome to our shop, what do you want (C, R, U, D)? ") if comment.upper()=="C": new_item = input("Enter new item: ") clouthes.append(new_item.capitalize()) elif comment.upper()=="R": print(end='') elif comment...
else: print("Sorry, your item is out of sale!") else: print("Allahu akbar! We're in reconstructing and can't serve you. See you again!") # items =[", "+clouthe for clouthe in clouthes if clouthes.index(clouthe)>0] # items.insert(0,clouthes[0]) # print("Our items: {0}".format(items)) # print("\n") print("...
clouthes.pop(pos-1)
conditional_block
weather.py
# Get weather data from various online sources # -*- coding: utf-8 -*- import requests from wrappers import * @plugin class yweather: @command("weather") def weather(self, message): """Get the current condition in a given location, from the Yahoo! Weather Service """ w = self.get_yaho...
else: return message.reply(data=w, text=w) def latlong(self, place): # Use Yahoo's yql to build the query if not place: raise Exception("You must provide a place name.") url = 'https://query.yahooapis.com/v1/public/yql?q=select centroid from geo.places(1) where tex...
message.reply(data=w, text="Current condition for {1}: {0[summary]} P({0[precipProbability]}) probability of precipitation. \ {0[temperature]}°C, feels like {0[apparentTemperature]}°C. Dew Point: {0[dewPoint]}°C. \ Humidity: {0[humidity]}. Wind Speed: {0[windSpeed]}mph bearing {0[windBearing]:03d}. \ ...
conditional_block
weather.py
# Get weather data from various online sources # -*- coding: utf-8 -*- import requests from wrappers import * @plugin class
: @command("weather") def weather(self, message): """Get the current condition in a given location, from the Yahoo! Weather Service """ w = self.get_yahoo_weather(message.data) if isinstance(w, dict): return message.reply(data=w, text="Weather for {0[...
yweather
identifier_name
weather.py
# Get weather data from various online sources # -*- coding: utf-8 -*- import requests from wrappers import * @plugin class yweather: @command("weather") def weather(self, message): """Get the current condition in a given location, from the Yahoo! Weather Service """ w = self.get_yaho...
@plugin class forecast_io: @command("whereis") def whereis(self, message): """Get the latitude and longitdue of a given place """ if not message: raise Exception("You must provide a place name.") ll = self.latlong(message.data) if isinstance(ll, ...
the pollen index for a given location """ if not message: raise Exception("You must provide a place name.") # Use Yahoo's yql to build the query yurl = 'https://query.yahooapis.com/v1/public/yql?q=select woeid from geo.places(1) where text = "' + message.data + '"&format=jso...
identifier_body
weather.py
# Get weather data from various online sources # -*- coding: utf-8 -*- import requests from wrappers import * @plugin class yweather: @command("weather") def weather(self, message): """Get the current condition in a given location, from the Yahoo! Weather Service """ w = self.get_yaho...
@command("pollen") def pollen(self, message): """Get the pollen index for a given location """ if not message: raise Exception("You must provide a place name.") # Use Yahoo's yql to build the query yurl = 'https://query.yahooapis.com/v1/public/yql?q=select woe...
class pollen:
random_line_split
a.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ '...
() { } /** * Defines the metadata of A * * @returns {object} metadata of A * */ mapper() { return { required: false, serializedName: 'A', type: { name: 'Composite', className: 'A', modelProperties: { statusCode: { required: false,...
constructor
identifier_name
a.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ '...
statusCode: { required: false, serializedName: 'statusCode', type: { name: 'String' } } } } }; } } module.exports = A;
random_line_split
settings_default.py
''' Created on Jun 20, 2016 @author: ionut ''' import logging logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s] - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) loggi...
#if MONTH or DATE are None we will use yesterday for searching MONTH = None DATE = None #Spotify settings SPOTIFY = { 'username': 'username', 'client_id': 'client_id', 'client_secret': 'client_secret', 'redirect_url': 'redirect_url', 'api_scopes': 'playlist-read-private playlist-modify-public play...
34, 44 ]
random_line_split
NodeSerializationCodes.py
from .Node import error SYNTAX_NODE_SERIALIZATION_CODES = { # 0 is 'Token'. Needs to be defined manually # 1 is 'Unknown'. Needs to be defined manually 'UnknownDecl': 2, 'TypealiasDecl': 3, 'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'Pou...
return SYNTAX_NODE_SERIALIZATION_CODES[syntax_kind]
identifier_body
NodeSerializationCodes.py
from .Node import error SYNTAX_NODE_SERIALIZATION_CODES = { # 0 is 'Token'. Needs to be defined manually # 1 is 'Unknown'. Needs to be defined manually 'UnknownDecl': 2, 'TypealiasDecl': 3,
'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'PoundSourceLocation': 8, 'ClassDecl': 9, 'StructDecl': 10, 'ProtocolDecl': 11, 'ExtensionDecl': 12, 'FunctionDecl': 13, 'InitializerDecl': 14, 'DeinitializerDecl': 15, 'SubscriptD...
random_line_split
NodeSerializationCodes.py
from .Node import error SYNTAX_NODE_SERIALIZATION_CODES = { # 0 is 'Token'. Needs to be defined manually # 1 is 'Unknown'. Needs to be defined manually 'UnknownDecl': 2, 'TypealiasDecl': 3, 'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'Pou...
(syntax_kind): return SYNTAX_NODE_SERIALIZATION_CODES[syntax_kind]
get_serialization_code
identifier_name
NodeSerializationCodes.py
from .Node import error SYNTAX_NODE_SERIALIZATION_CODES = { # 0 is 'Token'. Needs to be defined manually # 1 is 'Unknown'. Needs to be defined manually 'UnknownDecl': 2, 'TypealiasDecl': 3, 'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'Pou...
# Verify that no serialization code is used twice used_codes = set() for serialization_code in serialization_codes.values(): if serialization_code in used_codes: error("Serialization code %d used twice" % serialization_code) used_codes.add(serialization_code) def get_serializ...
if not node.is_base() and node.syntax_kind not in serialization_codes: error('Node %s has no serialization code' % node.syntax_kind)
conditional_block
lib.rs
#![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications)] #![doc(html_root_url = "https://cannon10100.github.io/factor_graph/")] //! Crate allowing creation and manipulation of ...
/// Render this graph to a Graphviz file pub fn render_to<W: Write>(&self, output: &mut W) { match dot::render(self, output) { Ok(_) => println!("Wrote factor graph"), Err(_) => panic!("An error occurred writing the factor graph"), } } /// Make a spanning tree ...
{ for var in variables.iter() { match self.variables.get_mut(var) { Some(var_obj) => { var_obj.add_factor(Factor::new(self.next_id,variables.clone(), func)); }, None => panic!("The variable {} was not found in the factor graph.", va...
identifier_body
lib.rs
#![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications)] #![doc(html_root_url = "https://cannon10100.github.io/factor_graph/")] //! Crate allowing creation and manipulation of ...
mod tests { use super::*; fn dummy_func(args: &[u32]) -> i32 { args.len() as i32 } #[test] #[should_panic] fn factor_with_nonexistent_var() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::f...
random_line_split
lib.rs
#![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications)] #![doc(html_root_url = "https://cannon10100.github.io/factor_graph/")] //! Crate allowing creation and manipulation of ...
<W: Write>(&self, root_var: &str, output: &mut W) { self.make_spanning_tree(root_var).render_to(output) } } #[cfg(test)] mod tests { use super::*; fn dummy_func(args: &[u32]) -> i32 { args.len() as i32 } #[test] #[should_panic] fn factor_with_nonexistent_var() { le...
render_spanning_tree_to
identifier_name
urls.py
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^render/(?P<photo_id>\d+)/$', 'render.views.raw'), url(r'^render/(?P<photo_id>\d+)/thumbnail/$', 'render.views...
# url(r'^fspot_browser/', include('fspot_browser.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), )
url(r'^hack/add_tag/(?P<photo_id>\d+)/(?P<tag_id>\d+)/$', 'browser.views.hack_add_tag'), url(r'^hack/remove_tag/(?P<photo_id>\d+)/(?P<tag_id>\d+)/$', 'browser.views.hack_remove_tag'), url(r'^hack/remove-best-tag/(?P<photo_id>\d+)/$', 'browser.views.hack_remove_best'), # Examples: # url(r'^$', 'fspot...
random_line_split
files_4.js
var searchData= [ ['ebert_5fgraph_2eh_0',['ebert_graph.h',['../ebert__graph_8h.html',1,'']]], ['element_2ecc_1',['element.cc',['../element_8cc.html',1,'']]], ['encoding_2ecc_2',['encoding.cc',['../encoding_8cc.html',1,'']]], ['encoding_2eh_3',['encoding.h',['../encoding_8h.html',1,'']]], ['encodingutils_2eh_4...
['expr_5farray_2ecc_10',['expr_array.cc',['../expr__array_8cc.html',1,'']]], ['expr_5fcst_2ecc_11',['expr_cst.cc',['../expr__cst_8cc.html',1,'']]], ['expressions_2ecc_12',['expressions.cc',['../expressions_8cc.html',1,'']]] ];
['entering_5fvariable_2ecc_5',['entering_variable.cc',['../entering__variable_8cc.html',1,'']]], ['entering_5fvariable_2eh_6',['entering_variable.h',['../entering__variable_8h.html',1,'']]], ['environment_2ecc_7',['environment.cc',['../environment_8cc.html',1,'']]], ['environment_2eh_8',['environment.h',['../en...
random_line_split
config.js
/* *-------------------------------------------------------------------- * jQuery-Plugin "freeesections -config.js-" * Version: 1.0 * Copyright (c) 2018 TIS * * Released under the MIT License. * http://tis2010.jp/license.txt * ------------------------------------------------------------------- */ jQuery.noCon...
break; } } }); /* initialize valiable */ if (Object.keys(config).length!==0) { $('select#id').val(config['id']); $('select#name').val(config['name']); $('select#shortcut1').val(config['shortcut1']); $('select#shortcut2').val(config['shortcut2']); $('input#fre...
{ $('select#name').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label)); $('select#shortcut1').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label)); $('select#shortcut2').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label)); ...
conditional_block
config.js
/* *-------------------------------------------------------------------- * jQuery-Plugin "freeesections -config.js-" * Version: 1.0 * Copyright (c) 2018 TIS * * Released under the MIT License. * http://tis2010.jp/license.txt * ------------------------------------------------------------------- */ jQuery.noCon...
$.merge(codes,functions.fieldsort(values.layout)); break; } }); return codes; } }; /*--------------------------------------------------------------- initialize fields ---------------------------------------------------------------*/ kintone.api(kintone.api.url('/k/v1/app/form/lay...
/* exclude spacer */ if (!values.elementId) codes.push(values.code); }); break; case 'GROUP':
random_line_split
c_cm1x.py
# ---------------------------------------------------------------------------- # Copyright (C) 2013-2014 Huynh Vi Lam <domovilam@gmail.com> # # This file is part of pimucha. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ----------------------------------------------------------------...
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of
random_line_split
support.component.ts
import { Component } from '@angular/core'; import { Location } from '@angular/common'; import { ToasterService } from 'angular2-toaster'; import { AuthService } from '../service/auth.service'; import { ApiService } from '../service/api.service'; import { SpinnerService } from '../service/spinner.service'; @Component...
/** * send() function * Send email */ send(): void { let message = { text: this.model.message, to: "emjovi@gmail.com", subject: "Prode de Amigos | Soporte" }; this.spinner.show(); this.api.sendMessage(this.auth.user.id, message)....
{ }
identifier_body
support.component.ts
import { Component } from '@angular/core'; import { Location } from '@angular/common'; import { ToasterService } from 'angular2-toaster'; import { AuthService } from '../service/auth.service'; import { ApiService } from '../service/api.service'; import { SpinnerService } from '../service/spinner.service'; @Component...
private spinner: SpinnerService ) { } /** * send() function * Send email */ send(): void { let message = { text: this.model.message, to: "emjovi@gmail.com", subject: "Prode de Amigos | Soporte" }; this.spinner.show(); ...
private api: ApiService, private location: Location, private toasterService: ToasterService,
random_line_split
support.component.ts
import { Component } from '@angular/core'; import { Location } from '@angular/common'; import { ToasterService } from 'angular2-toaster'; import { AuthService } from '../service/auth.service'; import { ApiService } from '../service/api.service'; import { SpinnerService } from '../service/spinner.service'; @Component...
( private auth: AuthService, private api: ApiService, private location: Location, private toasterService: ToasterService, private spinner: SpinnerService ) { } /** * send() function * Send email */ send(): void { let message = { text...
constructor
identifier_name
test_xml.py
from utile import pretty_xml, xml_to_dict, element_to_dict from testsuite.support import etree, TestCase import unittest XML_DATA = "<html><body><h1>test1</h1><h2>test2</h2></body></html>" XML_PRETTY = """\ <html> <body> <h1>test1</h1> <h2>test2</h2> </body> </html> """ XML_DICT = {'body': {'h2': 'test2',...
def test_element_to_dict(self): self.assertEqual(element_to_dict(etree.XML(XML_DATA)), XML_DICT) def test_xml_to_dict(self): self.assertEqual(xml_to_dict(XML_DATA), XML_DICT)
self.assertEqual(pretty_xml(XML_DATA), XML_PRETTY)
identifier_body
test_xml.py
from utile import pretty_xml, xml_to_dict, element_to_dict from testsuite.support import etree, TestCase
import unittest XML_DATA = "<html><body><h1>test1</h1><h2>test2</h2></body></html>" XML_PRETTY = """\ <html> <body> <h1>test1</h1> <h2>test2</h2> </body> </html> """ XML_DICT = {'body': {'h2': 'test2', 'h1': 'test1'}} @unittest.skipUnless(etree, 'lxml not installed') class XMLTestCase(TestCase): def ...
random_line_split
test_xml.py
from utile import pretty_xml, xml_to_dict, element_to_dict from testsuite.support import etree, TestCase import unittest XML_DATA = "<html><body><h1>test1</h1><h2>test2</h2></body></html>" XML_PRETTY = """\ <html> <body> <h1>test1</h1> <h2>test2</h2> </body> </html> """ XML_DICT = {'body': {'h2': 'test2',...
(self): self.assertEqual(xml_to_dict(XML_DATA), XML_DICT)
test_xml_to_dict
identifier_name
aliased.rs
use backend::Backend; use expression::{Expression, NonAggregate, SelectableExpression}; use query_builder::*; use query_builder::nodes::{Identifier, InfixNode}; use query_source::*; #[derive(Debug, Clone, Copy)] pub struct
<'a, Expr> { expr: Expr, alias: &'a str, } impl<'a, Expr> Aliased<'a, Expr> { pub fn new(expr: Expr, alias: &'a str) -> Self { Aliased { expr: expr, alias: alias, } } } pub struct FromEverywhere; impl<'a, T> Expression for Aliased<'a, T> where T: Expression...
Aliased
identifier_name
aliased.rs
use backend::Backend; use expression::{Expression, NonAggregate, SelectableExpression}; use query_builder::*; use query_builder::nodes::{Identifier, InfixNode}; use query_source::*; #[derive(Debug, Clone, Copy)] pub struct Aliased<'a, Expr> { expr: Expr, alias: &'a str, } impl<'a, Expr> Aliased<'a, Expr> { ...
fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult { out.push_identifier(&self.alias) } } // FIXME This is incorrect, should only be selectable from WithQuerySource impl<'a, T, QS> SelectableExpression<QS> for Aliased<'a, T> where Aliased<'a, T>: Expression, { } impl<'a, T: Expressio...
impl<'a, T, DB> QueryFragment<DB> for Aliased<'a, T> where DB: Backend, T: QueryFragment<DB>, {
random_line_split
aliased.rs
use backend::Backend; use expression::{Expression, NonAggregate, SelectableExpression}; use query_builder::*; use query_builder::nodes::{Identifier, InfixNode}; use query_source::*; #[derive(Debug, Clone, Copy)] pub struct Aliased<'a, Expr> { expr: Expr, alias: &'a str, } impl<'a, Expr> Aliased<'a, Expr> { ...
} pub struct FromEverywhere; impl<'a, T> Expression for Aliased<'a, T> where T: Expression, { type SqlType = T::SqlType; } impl<'a, T, DB> QueryFragment<DB> for Aliased<'a, T> where DB: Backend, T: QueryFragment<DB>, { fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult { ou...
{ Aliased { expr: expr, alias: alias, } }
identifier_body
font.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 euclid::{Point2D, Rect, Size2D}; use smallvec::SmallVec; use std::borrow::ToOwned; use std::cell::RefCell; use...
{ /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` ...
ShapingOptions
identifier_name
font.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 euclid::{Point2D, Rect, Size2D}; use smallvec::SmallVec; use std::borrow::ToOwned; use std::cell::RefCell; use...
} impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect::new(Point2D::new(Au(0), -ascent), Size2D::new(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent...
// this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au>
random_line_split
text_visual.py
import numpy as np import os from galry import log_debug, log_info, log_warn, get_color from fontmaps import load_font from visual import Visual __all__ = ['TextVisual'] VS = """ gl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x; gl_Position.y -= index * spacing.y / window_size.y; gl...
index = np.repeat(np.arange(len(self.textsizes)), self.textsizes) text_map = self.get_map(text) # offset for all characters in the merging of all texts offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) # for each text, ...
coordinates = [coordinates] * len(self.textsizes)
conditional_block
text_visual.py
import numpy as np import os from galry import log_debug, log_info, log_warn, get_color from fontmaps import load_font from visual import Visual __all__ = ['TextVisual'] VS = """ gl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x; gl_Position.y -= index * spacing.y / window_size.y; gl...
"""Template for displaying short text on a single line. It uses the following technique: each character is rendered as a sprite, i.e. a pixel with a large point size, and a single texture for every point. The texture contains a font atlas, i.e. all characters in a given font. Every point comes...
identifier_body
text_visual.py
import numpy as np import os from galry import log_debug, log_info, log_warn, get_color from fontmaps import load_font from visual import Visual __all__ = ['TextVisual'] VS = """ gl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x; gl_Position.y -= index * spacing.y / window_size.y; gl...
(self, coordinates=None): """Compound variable with the position of the text. All characters are at the exact same position, and are then shifted in the vertex shader.""" if coordinates is None: coordinates = (0., 0.) if type(coordinates) == tuple: ...
position_compound
identifier_name
text_visual.py
import numpy as np import os from galry import log_debug, log_info, log_warn, get_color from fontmaps import load_font from visual import Visual __all__ = ['TextVisual'] VS = """ gl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x; gl_Position.y -= index * spacing.y / window_size.y; gl...
vec2 coord = flat_text_map.xy + vec2(w * x, h * y); float letter_alpha = texture2D(tex_sampler, coord).a; out_color = color * letter_alpha; out_color.a = %s; } else out_color = vec4(0, 0, 0, 0); """ % background_transparent_shader return fs class TextVisual(Visual): """Template...
x = delta * x; if ((x >= 0) && (x <= 1)) { // coordinates of the character in the font atlas
random_line_split
three-effectcomposer.d.ts
import { WebGLRenderTarget, WebGLRenderer } from "./three-core"; import { ShaderPass } from "./three-shaderpass"; export class EffectComposer { constructor(renderer: WebGLRenderer, renderTarget?: WebGLRenderTarget); renderTarget1: WebGLRenderTarget; renderTarget2: WebGLRenderTarget; writeBuffer: WebGL...
// if set to true, the result of the pass is rendered to screen renderToScreen: boolean; setSize(width: number, height:number ): void; render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number, maskActive?: boolean): void; }
// if set to true, the pass indicates to swap read and write buffer after rendering needsSwap: boolean; // if set to true, the pass clears its buffer before rendering clear: boolean;
random_line_split
three-effectcomposer.d.ts
import { WebGLRenderTarget, WebGLRenderer } from "./three-core"; import { ShaderPass } from "./three-shaderpass"; export class EffectComposer { constructor(renderer: WebGLRenderer, renderTarget?: WebGLRenderTarget); renderTarget1: WebGLRenderTarget; renderTarget2: WebGLRenderTarget; writeBuffer: WebGL...
{ // if set to true, the pass is processed by the composer enabled: boolean; // if set to true, the pass indicates to swap read and write buffer after rendering needsSwap: boolean; // if set to true, the pass clears its buffer before rendering clear: boolean; // if set to true, the result of the pass is re...
Pass
identifier_name
toys.py
from minieigen import * from woo.dem import * import woo.core, woo.models from math import * import numpy class PourFeliciter(woo.core.Preprocessor,woo.pyderived.PyWooObject): '''Showcase for custom packing predicates, and importing surfaces from STL.''' _classTraits=None _PAT=woo.pyderived.PyAttrTrait # ...
pre=self S=woo.core.Scene(fields=[DemField(gravity=pre.gravity)],dtSafety=self.dtSafety) S.pre=pre.deepcopy() # preprocessor builds the simulation when called xx=numpy.linspace(0,(pre.nSpheres-1)*2*pre.rad,num=pre.nSpheres) mat=pre.model.mats[0] cabMat=(pre.model.mats[1]...
identifier_body
toys.py
from minieigen import * from woo.dem import * import woo.core, woo.models from math import * import numpy class PourFeliciter(woo.core.Preprocessor,woo.pyderived.PyWooObject): '''Showcase for custom packing predicates, and importing surfaces from STL.''' _classTraits=None _PAT=woo.pyderived.PyAttrTrait # ...
(self): # preprocessor builds the simulation when called pass class NewtonsCradle(woo.core.Preprocessor,woo.pyderived.PyWooObject): '''Showcase for custom packing predicates, and importing surfaces from STL.''' _classTraits=None _PAT=woo.pyderived.PyAttrTrait # less typing _attrTraits=[...
__call__
identifier_name
toys.py
from minieigen import * from woo.dem import * import woo.core, woo.models from math import * import numpy class PourFeliciter(woo.core.Preprocessor,woo.pyderived.PyWooObject): '''Showcase for custom packing predicates, and importing surfaces from STL.''' _classTraits=None _PAT=woo.pyderived.PyAttrTrait # ...
S.engines=DemField.minimalEngines(model=pre.model,dynDtPeriod=20)+[ IntraForce([In2_Truss_ElastMat()]), woo.core.PyRunner(self.plotEvery,'S.plot.addData(i=S.step,t=S.time,total=S.energy.total(),relErr=(S.energy.relErr() if S.step>1000 else 0),**S.energy)'), ] S.l...
color=min(.999,(x/xx[-1])) s=Sphere.make((x,0,0) if i>=pre.nFall else (x-ht*sin(pre.fallAngle),0,ht-ht*cos(pre.fallAngle)),radius=pre.rad,mat=mat,color=color) n=s.shape.nodes[0] S.dem.par.add(s) # sphere's node is integrated S.dem.nodesAppend(n) fo...
conditional_block
toys.py
from minieigen import * from woo.dem import * import woo.core, woo.models from math import * import numpy class PourFeliciter(woo.core.Preprocessor,woo.pyderived.PyWooObject): '''Showcase for custom packing predicates, and importing surfaces from STL.''' _classTraits=None _PAT=woo.pyderived.PyAttrTrait # ...
woo.core.Preprocessor.__init__(self) self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw) def __call__(self): pre=self S=woo.core.Scene(fields=[DemField(gravity=pre.gravity)],dtSafety=self.dtSafety) S.pre=pre.deepcopy() # preprocessor builds the simulation when ...
_PAT(int,'plotEvery',10,'How often to collect plot data'), _PAT(float,'dtSafety',.7,':obj:`woo.core.Scene.dtSafety`') ] def __init__(self,**kw):
random_line_split
periph_uart_if.py
# Copyright (c) 2018 Kevin Weiss, for HAW Hamburg <kevin.weiss@haw-hamburg.de> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. """@package PyToAPI This module handles parsing of information from RI...
raise ImportError('Cannot find riot_pal, try "pip install riot_pal"') class PeriphUartIf(DutShell): """Interface to the node with periph_uart firmware.""" def uart_init(self, dev, baud): """Initialize DUT's UART.""" return self.send_cmd("init {} {}".format(dev, baud)) def uart_mode(s...
except ImportError:
random_line_split
periph_uart_if.py
# Copyright (c) 2018 Kevin Weiss, for HAW Hamburg <kevin.weiss@haw-hamburg.de> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. """@package PyToAPI This module handles parsing of information from RI...
def uart_mode(self, dev, data_bits, parity, stop_bits): """Setup databits, parity and stopbits.""" return self.send_cmd( "mode {} {} {} {}".format(dev, data_bits, parity, stop_bits)) def uart_send_string(self, dev, test_string): """Send data via DUT's UART.""" retu...
"""Initialize DUT's UART.""" return self.send_cmd("init {} {}".format(dev, baud))
identifier_body
periph_uart_if.py
# Copyright (c) 2018 Kevin Weiss, for HAW Hamburg <kevin.weiss@haw-hamburg.de> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. """@package PyToAPI This module handles parsing of information from RI...
(self, dev, test_string): """Send data via DUT's UART.""" return self.send_cmd("send {} {}".format(dev, test_string))
uart_send_string
identifier_name
tag.component.ts
// Copyright (c) 2017 VMware, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applic...
toPromise<Tag[]>(this.tagService .getTags(this.repoName)) .then(items => { this.tags = items; this.loading = false; if (this.tags && this.tags.length === 0) { this.refreshRepo.emit(true); } }) .catch(error => { this.errorHandler.error(error)...
random_line_split
tag.component.ts
// Copyright (c) 2017 VMware, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applic...
implements OnInit, OnDestroy { @Input() projectId: number; @Input() repoName: string; @Input() isEmbedded: boolean; @Input() hasSignedIn: boolean; @Input() hasProjectAdminRole: boolean; @Input() registryUrl: string; @Input() withNotary: boolean; @Input() withClair: boolean; @Output() refreshRepo =...
TagComponent
identifier_name
tag.component.ts
// Copyright (c) 2017 VMware, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applic...
updateScanningStates(): void { toPromise<Tag[]>(this.tagService .getTags(this.repoName)) .then(items => { console.debug("updateScanningStates called!"); //Reset the scanning states this.tagsInScanning = {}; this.scanningTagCount = 0; items.forEach(item => { ...
{ //Double check if (this.tagsInScanning[tagId]) { return; } toPromise<any>(this.scanningService.startVulnerabilityScanning(this.repoName, tagId)) .then(() => { //Add to scanning map this.tagsInScanning[tagId] = tagId; //Counting this.scanningTagCount += 1; ...
identifier_body
tag.component.ts
// Copyright (c) 2017 VMware, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applic...
} retrieve() { this.tags = []; this.loading = true; toPromise<Tag[]>(this.tagService .getTags(this.repoName)) .then(items => { this.tags = items; this.loading = false; if (this.tags && this.tags.length === 0) { this.refreshRepo.emit(true); } ...
{ this.stateCheckTimer.unsubscribe(); }
conditional_block
__init__.py
from sys import exit, version_info import logging logger = logging.getLogger(__name__) try: from smbus import SMBus except ImportError: if version_info[0] < 3:
elif version_info[0] == 3: logger.warning("Falling back to mock SMBus. This library requires python3-smbus. Install with: sudo apt-get install python3-smbus") from picraftzero.thirdparty.mocks.raspiberrypi.rpidevmocks import Mock_smbusModule SMBus = Mock_smbusModule.SMBus from .pantilt import Pan...
logger.warning("Falling back to mock SMBus. This library requires python-smbus. Install with: sudo apt-get install python-smbus")
conditional_block
__init__.py
from sys import exit, version_info import logging logger = logging.getLogger(__name__) try: from smbus import SMBus except ImportError: if version_info[0] < 3: logger.warning("Falling back to mock SMBus. This library requires python-smbus. Install with: sudo apt-get install python-smbus") elif ver...
pan = pantilthat.servo_one tilt = pantilthat.servo_two
set_pixel_rgbw = pantilthat.set_pixel_rgbw show = pantilthat.show
random_line_split
card-harness.e2e.spec.ts
import {HarnessLoader} from '@angular/cdk/testing'; import {ProtractorHarnessEnvironment} from '@angular/cdk/testing/protractor'; import {MatCardHarness} from '@angular/material-experimental/mdc-card/testing/card-harness'; import {browser} from 'protractor'; describe('card harness', () => { let loader: HarnessLoader...
' Japan. A small, agile dog that copes very well with mountainous terrain, the Shiba Inu' + ' was originally bred for hunting.', 'LIKE', 'SHARE' ].join('\n')); }); it('should get title text', async () => { const card = await loader.getHarness(MatCardHarness); expect(await card.g...
expect(await card.getText()).toBe([ 'Shiba Inu', 'Dog Breed', 'The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from' +
random_line_split
hint.rs
use std::slice; use std::sync::Arc; use super::*; #[derive(Debug)] #[allow(dead_code)] pub enum StateOperation { Remove = 0, // _NET_WM_STATE_REMOVE Add = 1, // _NET_WM_STATE_ADD Toggle = 2, // _NET_WM_STATE_TOGGLE } impl From<bool> for StateOperation { fn from(op: bool) -> Self { if op { ...
pub fn set_wm_hints( &self, window: ffi::Window, wm_hints: XSmartPointer<'_, ffi::XWMHints>, ) -> Flusher<'_> { unsafe { (self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr); } Flusher::new(self) } pub fn get_normal_hints(&self, windo...
{ let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) }; self.check_errors()?; let wm_hints = if wm_hints.is_null() { self.alloc_wm_hints() } else { XSmartPointer::new(self, wm_hints).unwrap() }; Ok(wm_hints) }
identifier_body
hint.rs
use std::slice; use std::sync::Arc; use super::*; #[derive(Debug)] #[allow(dead_code)] pub enum StateOperation { Remove = 0, // _NET_WM_STATE_REMOVE Add = 1, // _NET_WM_STATE_ADD Toggle = 2, // _NET_WM_STATE_TOGGLE } impl From<bool> for StateOperation { fn from(op: bool) -> Self { if op { ...
}; unsafe { xconn.get_atom_unchecked(atom_name) } } } pub struct MotifHints { hints: MwmHints, } #[repr(C)] struct MwmHints { flags: c_ulong, functions: c_ulong, decorations: c_ulong, input_mode: c_long, status: c_ulong, } #[allow(dead_code)] mod mwm { use libc::c_ulon...
Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0",
random_line_split
hint.rs
use std::slice; use std::sync::Arc; use super::*; #[derive(Debug)] #[allow(dead_code)] pub enum StateOperation { Remove = 0, // _NET_WM_STATE_REMOVE Add = 1, // _NET_WM_STATE_ADD Toggle = 2, // _NET_WM_STATE_TOGGLE } impl From<bool> for StateOperation { fn from(op: bool) -> Self { if op { ...
else { self.size_hints.flags &= !ffi::PBaseSize; } } } impl XConnection { pub fn get_wm_hints( &self, window: ffi::Window, ) -> Result<XSmartPointer<'_, ffi::XWMHints>, XError> { let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) }; se...
{ self.size_hints.flags |= ffi::PBaseSize; self.size_hints.base_width = base_width as c_int; self.size_hints.base_height = base_height as c_int; }
conditional_block
hint.rs
use std::slice; use std::sync::Arc; use super::*; #[derive(Debug)] #[allow(dead_code)] pub enum StateOperation { Remove = 0, // _NET_WM_STATE_REMOVE Add = 1, // _NET_WM_STATE_ADD Toggle = 2, // _NET_WM_STATE_TOGGLE } impl From<bool> for StateOperation { fn from(op: bool) -> Self { if op { ...
(&mut self, maximizable: bool) { if maximizable { self.add_func(mwm::MWM_FUNC_MAXIMIZE); } else { self.remove_func(mwm::MWM_FUNC_MAXIMIZE); } } fn add_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS != 0 { if se...
set_maximizable
identifier_name
reflection_capabilities.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Type, isType} from '../interface/type'; import {ANNOTATIONS, PARAMETERS, PROP_METADATA} from '../util/decora...
return null; } annotations(typeOrFunc: Type<any>): any[] { if (!isType(typeOrFunc)) { return []; } const parentCtor = getParentCtor(typeOrFunc); const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || []; const parentAnnotations = parentCtor !== Object ? this.annotatio...
{ return (typeOrFunc as any)[ANNOTATIONS]; }
conditional_block
reflection_capabilities.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Type, isType} from '../interface/type'; import {ANNOTATIONS, PARAMETERS, PROP_METADATA} from '../util/decora...
<T>(t: Type<T>): (args: any[]) => T { return (...args: any[]) => new t(...args); } /** @internal */ _zipTypesAndAnnotations(paramTypes: any[], paramAnnotations: any[]): any[][] { let result: any[][]; if (typeof paramTypes === 'undefined') { result = new Array(paramAnnotations.length); } else { ...
factory
identifier_name
reflection_capabilities.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Type, isType} from '../interface/type'; import {ANNOTATIONS, PARAMETERS, PROP_METADATA} from '../util/decora...
} return result; } private _ownParameters(type: Type<any>, parentCtor: any): any[][]|null { const typeStr = type.toString(); // If we have no decorators, we only have function.length as metadata. // In that case, to detect whether a child class declared an own constructor or not, // we need...
result[i] = []; } if (paramAnnotations && paramAnnotations[i] != null) { result[i] = result[i].concat(paramAnnotations[i]); }
random_line_split
reflection_capabilities.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Type, isType} from '../interface/type'; import {ANNOTATIONS, PARAMETERS, PROP_METADATA} from '../util/decora...
resourceUri(type: any): string { return `./${stringify(type)}`; } resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any { return runtime; } resolveEnum(enumIdentifier: any, name: string): any { return enumIdentifier[name]; } } function convertTsickleDecoratorIntoMetada...
{ // StaticSymbol if (typeof type === 'object' && type['filePath']) { return type['filePath']; } // Runtime type return `./${stringify(type)}`; }
identifier_body
github.py
""" Github Authentication """ import httplib2 from django.conf import settings from django.core.mail import send_mail from oauth2client.client import OAuth2WebServerFlow from helios_auth import utils # some parameters to indicate that status updating is not possible STATUS_UPDATES = False # display tweaks LOGIN_ME...
def get_auth_url(request, redirect_url): flow = get_flow(redirect_url) request.session['gh_redirect_uri'] = redirect_url return flow.step1_get_authorize_url() def get_user_info_after_auth(request): redirect_uri = request.session['gh_redirect_uri'] del request.session['gh_redirect_uri'] flow = get_flow(re...
return OAuth2WebServerFlow( client_id=settings.GH_CLIENT_ID, client_secret=settings.GH_CLIENT_SECRET, scope='read:user user:email', auth_uri="https://github.com/login/oauth/authorize", token_uri="https://github.com/login/oauth/access_token", redirect_uri=redirect_url, )
identifier_body
github.py
""" Github Authentication """ import httplib2 from django.conf import settings from django.core.mail import send_mail from oauth2client.client import OAuth2WebServerFlow from helios_auth import utils # some parameters to indicate that status updating is not possible STATUS_UPDATES = False # display tweaks LOGIN_ME...
def do_logout(user): return None def update_status(token, message): pass def send_message(user_id, name, user_info, subject, body): send_mail( subject, body, settings.SERVER_EMAIL, ["%s <%s>" % (user_id, user_info['email'])], fail_silently=False, ) def check_constraint(eligibility, user_i...
}
random_line_split
github.py
""" Github Authentication """ import httplib2 from django.conf import settings from django.core.mail import send_mail from oauth2client.client import OAuth2WebServerFlow from helios_auth import utils # some parameters to indicate that status updating is not possible STATUS_UPDATES = False # display tweaks LOGIN_ME...
(user_id, user_info): return True
can_create_election
identifier_name
github.py
""" Github Authentication """ import httplib2 from django.conf import settings from django.core.mail import send_mail from oauth2client.client import OAuth2WebServerFlow from helios_auth import utils # some parameters to indicate that status updating is not possible STATUS_UPDATES = False # display tweaks LOGIN_ME...
if not user_email: raise Exception("email address with GitHub not verified") return { 'type': 'github', 'user_id': user_id, 'name': '%s (%s)' % (user_id, user_name), 'info': {'email': user_email}, 'token': {}, } def do_logout(user): return None def update_status(token, message): pa...
user_email = email['email'] break
conditional_block
input.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
let ref key_str: Option<String> = keyval[0]; let ref val_str: Option<String> = keyval[1]; let key = match *key_str { Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(ref k) => Bytes::new(k.clone().into_bytes()), None => { break; } }; let val = ma...
{ return Err(Error::custom("Invalid key value pair.")); }
conditional_block
input.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
<D>(deserializer: &mut D) -> Result<Self, D::Error> where D: Deserializer { deserializer.deserialize(InputVisitor) } } struct InputVisitor; impl Visitor for InputVisitor { type Value = Input; fn visit_map<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapVisitor { let mut result = ...
deserialize
identifier_name
input.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
try!(visitor.end()); let input = Input { data: result }; Ok(input) } } #[cfg(test)] mod tests { use std::collections::BTreeMap; use serde_json; use bytes::Bytes; use super::Input; #[test] fn input_deserialization_from_map() { let s = r#"{ "0x0045" : "0x0123456789", "be" : "e", "0x0a" :...
}; result.insert(key, val); }
random_line_split
conf.py
import os import string import random from fabric.api import env from fabric.colors import green from literals import (DEFAULT_INSTALL_PATH, DEFAULT_VIRTUALENV_NAME, DEFAULT_REPOSITORY_NAME, DEFAULT_OS, OS_CHOICES,
def password_generator(): # http://snipplr.com/view/63223/python-password-generator/ chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for x in range(DEFAULT_PASSWORD_LENGTH)) @reduce_env def setup_environment(): env['os'] = getattr(env, 'os', DEFAULT_OS) env['os_na...
DEFAULT_DATABASE_MANAGER, DB_CHOICES, DEFAULT_DATABASE_NAME, DEFAULT_WEBSERVER, WEB_CHOICES, DEFAULT_DATABASE_USERNAME, DJANGO_DB_DRIVERS, DEFAULT_DATABASE_HOST, DEFAULT_PASSWORD_LENGTH) from server_config import reduce_env
random_line_split
conf.py
import os import string import random from fabric.api import env from fabric.colors import green from literals import (DEFAULT_INSTALL_PATH, DEFAULT_VIRTUALENV_NAME, DEFAULT_REPOSITORY_NAME, DEFAULT_OS, OS_CHOICES, DEFAULT_DATABASE_MANAGER, DB_CHOICES, DEFAULT_DATABASE_NAME, DEFAULT_WEBSERVER, WEB_CHOIC...
(): # http://snipplr.com/view/63223/python-password-generator/ chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for x in range(DEFAULT_PASSWORD_LENGTH)) @reduce_env def setup_environment(): env['os'] = getattr(env, 'os', DEFAULT_OS) env['os_name'] = OS_CHOICES[env.o...
password_generator
identifier_name
conf.py
import os import string import random from fabric.api import env from fabric.colors import green from literals import (DEFAULT_INSTALL_PATH, DEFAULT_VIRTUALENV_NAME, DEFAULT_REPOSITORY_NAME, DEFAULT_OS, OS_CHOICES, DEFAULT_DATABASE_MANAGER, DB_CHOICES, DEFAULT_DATABASE_NAME, DEFAULT_WEBSERVER, WEB_CHOIC...
env['database_name'] = getattr(env, 'database_name', DEFAULT_DATABASE_NAME) env['webserver'] = getattr(env, 'webserver', DEFAULT_WEBSERVER) env['webserver_name'] = WEB_CHOICES[env.webserver] env['django_database_driver'] = DJANGO_DB_DRIVERS[env.database_manager] def print_supported_configs...
print('Must set the database_manager_admin_password entry in the fabric settings file (~/.fabricrc by default)') exit(1)
conditional_block
conf.py
import os import string import random from fabric.api import env from fabric.colors import green from literals import (DEFAULT_INSTALL_PATH, DEFAULT_VIRTUALENV_NAME, DEFAULT_REPOSITORY_NAME, DEFAULT_OS, OS_CHOICES, DEFAULT_DATABASE_MANAGER, DB_CHOICES, DEFAULT_DATABASE_NAME, DEFAULT_WEBSERVER, WEB_CHOIC...
print('Supported operating systems (os=): %s, default=\'%s\'' % (dict(OS_CHOICES).keys(), green(DEFAULT_OS))) print('Supported database managers (database_manager=): %s, default=\'%s\'' % (dict(DB_CHOICES).keys(), green(DEFAULT_DATABASE_MANAGER))) print('Supported webservers (webserver=): %s, default=\'%s\'' % ...
identifier_body
htmlstyleelement.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 cssparser::{Parser as CssParser, ParserInput}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen...
impl HTMLStyleElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefi...
any_failed_load: Cell<bool>, line_number: u64, }
random_line_split
htmlstyleelement.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 cssparser::{Parser as CssParser, ParserInput}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen...
(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if !succeeded { self.any_failed_load.set(true); } self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get() != 0 { return None; ...
load_finished
identifier_name
htmlstyleelement.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 cssparser::{Parser as CssParser, ParserInput}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen...
}
{ self.get_cssom_stylesheet().map(DomRoot::upcast) }
identifier_body
htmlstyleelement.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 cssparser::{Parser as CssParser, ParserInput}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen...
self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get() != 0 { return None; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { sel...
{ self.any_failed_load.set(true); }
conditional_block
entity-schema-target.ts
import "reflect-metadata"; import {closeTestingConnections, createTestingConnections, reloadTestingDatabases} from "../../../utils/test-utils"; import {Connection} from "../../../../src"; import {PostEntity} from "./entity/PostEntity"; import {Post} from "./model/Post"; describe("entity schemas > target option", () =>...
});
random_line_split
geoWidgets.py
# -*- coding: ISO-8859-1 -*- """ Form Widget classes specific to the geoSite admin site. """ # A class that corresponds to an HTML form widget, # e.g. <input type="text"> or <textarea>. # This handles rendering of the widget as HTML. import json from django.template.loader import render_to_string from .conf import ...
if value: return [value.lat, value.lng] return [None,None] def format_output(self, rendered_widgets): return render_to_string('geopositionmap/widgets/geopositionmap.html', { 'latitude': { 'html': rendered_widgets[0], 'label': ...
return value.rsplit(',')
conditional_block
geoWidgets.py
# -*- coding: ISO-8859-1 -*- """ Form Widget classes specific to the geoSite admin site. """ # A class that corresponds to an HTML form widget, # e.g. <input type="text"> or <textarea>. # This handles rendering of the widget as HTML. import json from django.template.loader import render_to_string from .conf import ...
)
random_line_split
geoWidgets.py
# -*- coding: ISO-8859-1 -*- """ Form Widget classes specific to the geoSite admin site. """ # A class that corresponds to an HTML form widget, # e.g. <input type="text"> or <textarea>. # This handles rendering of the widget as HTML. import json from django.template.loader import render_to_string from .conf import ...
: #extend = False css = { 'all': ( 'geopositionmap/geopositionmap.css', '//cdn.leafletjs.com/leaflet-0.7.3/leaflet.css', ) } js = ( '//maps.google.com/maps/api/js?sensor=false', '//cdn.leaflet...
Media
identifier_name
geoWidgets.py
# -*- coding: ISO-8859-1 -*- """ Form Widget classes specific to the geoSite admin site. """ # A class that corresponds to an HTML form widget, # e.g. <input type="text"> or <textarea>. # This handles rendering of the widget as HTML. import json from django.template.loader import render_to_string from .conf import ...
def decompress(self, value): if isinstance(value, six.text_type): return value.rsplit(',') if value: return [value.lat, value.lng] return [None,None] def format_output(self, rendered_widgets): return render_to_string('geopositionmap/widg...
widgets = ( forms.TextInput(), forms.TextInput(), ) super(LatLngTextInputWidget, self).__init__(widgets, attrs)
identifier_body
crate-method-reexport-grrrrrrr.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-MI...
{ use crate_method_reexport_grrrrrrr2::rust::add; use crate_method_reexport_grrrrrrr2::rust::cx; let x: Box<_> = box () (); x.cx(); let y = (); y.add("hi".to_string()); }
identifier_body
crate-method-reexport-grrrrrrr.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-MI...
// aux-build:crate-method-reexport-grrrrrrr2.rs extern crate crate_method_reexport_grrrrrrr2; pub fn main() { use crate_method_reexport_grrrrrrr2::rust::add; use crate_method_reexport_grrrrrrr2::rust::cx; let x: Box<_> = box () (); x.cx(); let y = (); y.add("hi".to_string()); }
// This is a regression test that the metadata for the // name_pool::methods impl in the other crate is reachable from this // crate.
random_line_split
crate-method-reexport-grrrrrrr.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-MI...
() { use crate_method_reexport_grrrrrrr2::rust::add; use crate_method_reexport_grrrrrrr2::rust::cx; let x: Box<_> = box () (); x.cx(); let y = (); y.add("hi".to_string()); }
main
identifier_name
issuer_parameters.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(Model): """Parameters for the issuer of the X509 component of a certificate. :param name: Name of the referenced issuer object or reserved names; for example, 'Self' or 'Unknown'. :type name: str :param certificate_type: Type of certificate to be requested from the issuer provider. :type...
IssuerParameters
identifier_name
issuer_parameters.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
self.name = name self.certificate_type = certificate_type
identifier_body
issuer_parameters.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
class IssuerParameters(Model): """Parameters for the issuer of the X509 component of a certificate. :param name: Name of the referenced issuer object or reserved names; for example, 'Self' or 'Unknown'. :type name: str :param certificate_type: Type of certificate to be requested from the is...
random_line_split
test_pyc.py
""" Test completions from *.pyc files: - generate a dummy python module - compile the dummy module to generate a *.pyc - delete the pure python dummy module - try jedi on the generated *.pyc """ import compileall import os import shutil import sys import jedi from ..helpers import cwd_at
SRC = """class Foo: pass class Bar: pass """ def generate_pyc(): os.mkdir("dummy_package") with open("dummy_package/__init__.py", 'w'): pass with open("dummy_package/dummy.py", 'w') as f: f.write(SRC) compileall.compile_file("dummy_package/dummy.py") os.remove("dummy_pack...
random_line_split
test_pyc.py
""" Test completions from *.pyc files: - generate a dummy python module - compile the dummy module to generate a *.pyc - delete the pure python dummy module - try jedi on the generated *.pyc """ import compileall import os import shutil import sys import jedi from ..helpers import cwd_at SRC = """class Foo: ...
(): os.mkdir("dummy_package") with open("dummy_package/__init__.py", 'w'): pass with open("dummy_package/dummy.py", 'w') as f: f.write(SRC) compileall.compile_file("dummy_package/dummy.py") os.remove("dummy_package/dummy.py") if sys.version_info[0] == 3: # Python3 specif...
generate_pyc
identifier_name
test_pyc.py
""" Test completions from *.pyc files: - generate a dummy python module - compile the dummy module to generate a *.pyc - delete the pure python dummy module - try jedi on the generated *.pyc """ import compileall import os import shutil import sys import jedi from ..helpers import cwd_at SRC = """class Foo: ...
test_pyc()
conditional_block
test_pyc.py
""" Test completions from *.pyc files: - generate a dummy python module - compile the dummy module to generate a *.pyc - delete the pure python dummy module - try jedi on the generated *.pyc """ import compileall import os import shutil import sys import jedi from ..helpers import cwd_at SRC = """class Foo: ...
@cwd_at('test/test_evaluate') def test_pyc(): """ The list of completion must be greater than 2. """ try: generate_pyc() s = jedi.Script("from dummy_package import dummy; dummy.", path='blub.py') assert len(s.completions()) >= 2 finally: shutil.rmtree("dummy_packag...
os.mkdir("dummy_package") with open("dummy_package/__init__.py", 'w'): pass with open("dummy_package/dummy.py", 'w') as f: f.write(SRC) compileall.compile_file("dummy_package/dummy.py") os.remove("dummy_package/dummy.py") if sys.version_info[0] == 3: # Python3 specific: ...
identifier_body
Admins.test.ts
import { shallowMount } from '@vue/test-utils'; import T from '../../lang'; import common_Admins from './Admins.vue'; describe('Admins.vue', () => { it('Should handle empty admins list', () => { const wrapper = shallowMount(common_Admins, { propsData: { hasParentComponent: false, initialA...
propsData: { hasParentComponent: false, initialAdmins: [ { role: 'owner', user_id: 1, username: 'admin-username' }, { role: 'site-admin', user_id: 2, username: 'site-admin-username' }, { role: 'admin', user_id: 3, username: 'user-username' }, ], }, }...
random_line_split
App.js
'use strict'; import React,{ Component } from 'react'; import { StyleSheet, AppState, Dimensions, Image } from 'react-native'; import CodePush from 'react-native-code-push'; import { Container, Text, View, InputGroup, Input, Icon } from 'native-base'; import Modal from 'react-native-modalbox'; import AppNavigator fr...
var height = Dimensions.get('window').height; let styles = StyleSheet.create({ container: { flex: 1, width: null, height: null }, box: { padding: 10, backgroundColor: 'transparent', flex: 1, height: height-70 }, space: { marginTop: 10, ...
random_line_split