file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
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 self.n_x_tiles = n_x_tiles self.n_y_tiles = n_y_tiles self.n_tilings = n_tilings self.n_actions = n_actions if self.n_x_tiles % 1 != 0 or self.n_x_tiles <= 0: raise TypeError("Number of x tiles must be a positive natural number instead of {}".format(self.n_x_tiles)) if self.n_y_tiles % 1 != 0 or self.n_y_tiles <= 0: raise TypeError("Number of y tiles must be a positive natural number instead of {}".format(self.n_y_tiles)) self.tile_width = (self.x_high - self.x_low) / self.n_x_tiles self.tile_height = (self.y_high - self.y_low) / self.n_y_tiles self.tiling_width = self.tile_width * self.n_x_tiles self.tiling_height = self.tile_height * self.n_y_tiles self.tile_starts: List[Tuple[float, float]] = [] # Each tiling starts at a random offset that is a fraction of the tile width and height for _ in range(self.n_tilings): self.tile_starts.append(( self.x_low + np.random.rand() * self.tile_width, self.y_low + np.random.rand() * self.tile_height)) 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 action.""" summed = 0 for i in range(self.n_tilings): shifted = state - self.tile_starts[i] # Subtract the randomly chosen offsets x, y = shifted if (x >= 0 and x <= self.tiling_width) and (y >= 0 and y <= self.tiling_height): summed += self.thetas[i][int(y // self.tile_height)][int(x // self.tile_width)][action]
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 if(x >= 0 and x <= self.tiling_width) and(y >= 0 and y <= self.tiling_height): # Set the feature to active result[i][int(y // self.tile_height)][int(x // self.tile_width)][action] = 1 return result
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):
self.tiling_width = self.tile_width * self.n_x_tiles self.tiling_height = self.tile_height * self.n_y_tiles self.tile_starts: List[Tuple[float, float]] = [] # Each tiling starts at a random offset that is a fraction of the tile width and height for _ in range(self.n_tilings): self.tile_starts.append(( self.x_low + np.random.rand() * self.tile_width, self.y_low + np.random.rand() * self.tile_height)) 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 action.""" summed = 0 for i in range(self.n_tilings): shifted = state - self.tile_starts[i] # Subtract the randomly chosen offsets x, y = shifted if (x >= 0 and x <= self.tiling_width) and (y >= 0 and y <= self.tiling_height): summed += self.thetas[i][int(y // self.tile_height)][int(x // self.tile_width)][action] return summed 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 if(x >= 0 and x <= self.tiling_width) and(y >= 0 and y <= self.tiling_height): # Set the feature to active result[i][int(y // self.tile_height)][int(x // self.tile_width)][action] = 1 return result
"""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 self.n_x_tiles = n_x_tiles self.n_y_tiles = n_y_tiles self.n_tilings = n_tilings self.n_actions = n_actions if self.n_x_tiles % 1 != 0 or self.n_x_tiles <= 0: raise TypeError("Number of x tiles must be a positive natural number instead of {}".format(self.n_x_tiles)) if self.n_y_tiles % 1 != 0 or self.n_y_tiles <= 0: raise TypeError("Number of y tiles must be a positive natural number instead of {}".format(self.n_y_tiles)) self.tile_width = (self.x_high - self.x_low) / self.n_x_tiles self.tile_height = (self.y_high - self.y_low) / self.n_y_tiles
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> { loop { match self.chars.next() { Some((i, ' ')) => return Some(Ok((i, Tok::Space, i+1))), Some((i, '\t')) => return Some(Ok((i, Tok::Tab, i+1))), Some((i, '\n')) => return Some(Ok((i, Tok::Linefeed, i+1))), None => return None, // End of file _ => continue, // Comment; skip this character } } } } #[test] fn skip_comments() { let source = "The quick brown fox jumped over the lazy dog"; assert_eq!(Lexer::new(source).count(), 8); assert!(Lexer::new(source).all(|tok| match tok { Ok((_, Tok::Space, _)) => true, _ => false, })); }
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> { pub fn new(input: &'input str) -> Self {
} } 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 Some(Ok((i, Tok::Tab, i+1))), Some((i, '\n')) => return Some(Ok((i, Tok::Linefeed, i+1))), None => return None, // End of file _ => continue, // Comment; skip this character } } } } #[test] fn skip_comments() { let source = "The quick brown fox jumped over the lazy dog"; assert_eq!(Lexer::new(source).count(), 8); assert!(Lexer::new(source).all(|tok| match tok { Ok((_, Tok::Space, _)) => true, _ => false, })); }
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 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('title'), number: this.model.get('number'), state: this.model.get('state') }); this.$el.append(issueMetaInfoView.render().$el); // Append a reporter to this view. var reporter = this.model.get('user'); var reporterView = new ReporterView(reporter); this.$el.append(reporterView.render().$el); // Append summary text to this view. var summaryText = this.model.get('body'); if (summaryText !== null && summaryText.length > 0)
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('title'), number: this.model.get('number'), state: this.model.get('state') }); this.$el.append(issueMetaInfoView.render().$el); // Append a reporter to this view. var reporter = this.model.get('user'); var reporterView = new ReporterView(reporter); this.$el.append(reporterView.render().$el); // Append summary text to this view. var summaryText = this.model.get('body'); if (summaryText !== null && summaryText.length > 0) { var shortSummaryModel = new ShortSummaryModel({ text: summaryText }); var shortSummaryView = new ShortSummaryView({ model: shortSummaryModel }); this.$el.append(shortSummaryView.render().$el); } return this; } });
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, 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. """Performance analyzer constants.""" DISPLAY_COLUMNS = [ { 'name': 'type', 'title': 'Issue type', 'tooltip': 'Type of issue affecting the fuzz target.' }, { 'name': 'percent', 'title': 'Percent runs affected', 'tooltip': 'Percentage of fuzz target runs impacted by this issue.' },
'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 fix this issue.' }, ] ISSUE_TYPE_SOLUTIONS_MAP = { 'bad_instrumentation': """The fuzz target has been built incorrectly. Fuzzing engine has not detected coverage information, so most likely coverage flags (i.e. `-fsanitize-coverage`) have not been properly used during compilation.).""", 'coverage': """The fuzz target cannot find new 'interesting' inputs and hence unable to cover new code. There are several ways to improve code coverage:<br/> - Add a new dictionary or update existing ones with new strings.<br/> - Add new testcases to the corpus (these can be manually generated, used from unit tests, valid files, traffic streams, etc depending on the target).<br/> - Update the target function to use different combinations of flags passed to the target.<br/> - Check `max_len` value, may be it is not appropriate for the target (too big for some data which cannot be too big, or too small for some data which cannot be too small).""", 'crash': """The fuzz target crashes frequently. You need to fix these crashers first so that fuzzing can be efficient and explore new code and crashes.""", 'leak': """The fuzz target is leaking memory often. You need to fix these leaks first so that fuzzing can be efficient and not crash on out-of-memory. If these leaks are false positives, you can suppress them using LeakSanitizer suppressions.""", 'logging': """The fuzz target writes too many log messages (either stdout or stderr). Excessive logging is extremely detrimental to efficient fuzzing. Most targets support different levels of logging for a target. You need to modify the target function or compilation flags to use the lowest level of logging verbosity.<br/> If target does not provide a way to control logging levels or to disable logging in any other possible way, you can use `-close_fd_mask` option of libFuzzer.""", 'none': """The fuzz target is working well. No issues were detected.""", 'oom': """The fuzz target hits out-of-memory errors. It may be caused by a valid input (e.g. a large array allocation). In that case, you need to implement a workaround to avoid generation of such testcases. Or the target function could be leaking memory, so you need to fix those memory leak crashes.""", 'slow_unit': """The target spends several seconds on a single input. It can a bug in the target, so you need to profile whether this is a real bug in the target. For some cases, lowering `max_len` option may help to avoid slow units (e.g. regexp processing time increases exponentially with larger inputs).""", 'speed': """Execution speed is one of the most important factors for efficient fuzzing. You need to optimize the target function so that the execution speed is at least 1,000 testcases per second.""", 'startup_crash': """The fuzz target does not work and crashes instantly on startup. Compile the fuzz target locally and run it as per the documentation. In most cases, fuzz target does not work due to linking errors or due to the bug in target itself (i.e. `LLVMFuzzerTestOneInput` function).""", 'timeout': """The fuzz target hits timeout error. Timeout bugs slow down fuzzing significantly since fuzz target hangs on the processing of those inputs. You need to debug the root cause for the hang and fix it. Possible causes are getting stuck on an infinite loop, some complex computation, etc.""", } QUERY_COLUMNS = [ 'actual_duration', 'average_exec_per_sec', 'bad_instrumentation', 'crash_count', 'expected_duration', 'leak_count', 'log_lines_from_engine', 'log_lines_ignored', 'log_lines_unwanted', 'new_units_added', 'new_units_generated', 'oom_count', 'slow_units_count', 'startup_crash_count', 'strategy_corpus_subset', 'strategy_random_max_len', 'strategy_value_profile', 'timeout_count', 'timestamp', ]
{ '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.upper()=="U": pos = int(input("Update position? ")) if pos <= len(clouthes): new_item = input("Enter new item: ") clouthes[pos-1] = new_item.capitalize() else: print("Sorry, your item is out of sale!") elif comment.upper()=="D": pos = int(input("Delete position? ")) if pos <= len(clouthes): clouthes.pop(pos-1) 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("Our items: ",end='') for item in clouthes: if clouthes.index(item)<len(clouthes)-1: print(item,end=', ') else: print(item+"\n")
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.upper()=="U": pos = int(input("Update position? ")) if pos <= len(clouthes): new_item = input("Enter new item: ") clouthes[pos-1] = new_item.capitalize() else: print("Sorry, your item is out of sale!") elif comment.upper()=="D": pos = int(input("Delete position? ")) if pos <= len(clouthes):
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("Our items: ",end='') for item in clouthes: if clouthes.index(item)<len(clouthes)-1: print(item,end=', ') else: print(item+"\n")
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_yahoo_weather(message.data) if isinstance(w, dict): return message.reply(data=w, text="Weather for {0[city]}, {0[country]}: {0[condition]}, {0[temperature]}. Wind Speed: {0[wind_speed]} ({0[wind_direction]}), Wind Chill: {0[wind_chill]}. Visibility {0[visibility]}. High Temp: {0[high]}°C, Low Temp: {0[low]}°C. Sunrise: {0[sunrise]}, Sunset: {0[sunset]}.".format(w) ) else: return message.reply(data=w, text=w) @command("forecast") def forecast(self, message): """Get the 5 day forcast for a given location, from the Yahoo! Weather Service """ w = self.get_yahoo_weather(message.data) if isinstance(w, dict): return message.reply(data=w['forecast'], text="; ".join(["{0[day]}: {0[condition]}. High: {0[high]}, Low: {0[low]}.".format(x) for x in w['forecast']])) else: return message.reply(data=w, text=w) def get_yahoo_weather(self, place): if not place: raise Exception("You must provide a place name.") # Use Yahoo's yql to build the query url = 'https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in(select woeid from geo.places(1) where text="' + place + '") and u="c"&format=json' # Fetch the results r = requests.get(url) json = r.json() result = json['query']['results'] if not result: return "No weather could be found for " + place + "." # Read the pertinant parts of the result, and format them nicely. channel = result['channel'] city = channel['location']['city'] country = channel['location']['country'] region = channel['location']['region'] high = channel['item']['forecast'][0]['high'] low = channel['item']['forecast'][0]['low'] # There's a bug in the weather API where windchill is reported as "feels like" in farenheight. feelsLike = (float(channel['wind']['chill']) - 32) / 1.8 chill = feelsLike - float(channel['item']['condition']['temp']) windChill = "{0:.2f}°{1}".format(chill, channel['units']['temperature']) windDir = "{0:03d}deg".format(int(channel['wind']['direction'])) windSpeed = "{0} {1}".format(channel['wind']['speed'], channel['units']['speed']) humidity = "{0}%".format(channel['atmosphere']['humidity']) pressure = "{0}{1}".format(channel['atmosphere']['pressure'], channel['units']['pressure']) rising = channel['atmosphere']['rising'] visibility = "{0}{1}".format(channel['atmosphere']['visibility'], channel['units']['distance']) sunrise = channel['astronomy']['sunrise'] sunset = channel['astronomy']['sunset'] condition = channel['item']['condition']['text'] temperature = "{0}°{1}".format(channel['item']['condition']['temp'], channel['units']['temperature']) forecast = [] for pred in channel['item']['forecast']: c = {"day": pred['day'], "condition": pred['text'], "high": "{0}°{1}".format(pred['high'], channel['units']['temperature']), "low": "{0}°{1}".format(pred['low'], channel['units']['temperature'])} forecast.append(c) return {"city":city, "country":country, "region":region, "high":high, "low":low, "temperature": temperature, "wind_chill":windChill, "wind_direction":windDir, "wind_speed":windSpeed, "humidity":humidity, "pressure":pressure, "rising":rising, "visibility":visibility, "sunrise":sunrise, "sunset":sunset, "condition":condition, "forecast":forecast } @plugin class pollen: @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 woeid from geo.places(1) where text = "' + message.data + '"&format=json' # Fetch the results r = requests.get(yurl) json = r.json() if not json['query']['results']: return "Could not find " + place + "." woeid = json['query']['results']['place']['woeid'] print(woeid) purl = "https://pollencheck.p.mashape.com/api/1/forecasts/" + woeid headers = { "X-Mashape-Key": "O6cwEp209Jmsh614NhNE6DpXIUKhp1npOMrjsnvWzdpgHYgzob", "Accept": "application/json" } pollen_data = requests.get(purl, headers=headers) p_json = pollen_data.json() if not p_json: raise Exception("Could not get data for '" + message.data + "', try a large city.") return message.reply(data=p_json, text="Total pollen count: {0[maxLevel]}".format(p_json['periods'][0]['combined'])) @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, dict): return message.reply(data=ll, text="Latitude: {}, Longitude: {}".format(ll['latitude'], ll['longitude'])) else: return message.reply(data=ll, text=ll) @command("condition") def condition(self, message): """Get the current weather using the https://developer.forecast.io/docs/v2 API. """ if not message: raise Exception("You must provide a place name.") w = self.get_forecast_io_weather(message.data) if isinstance(w, dict): return
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 text = "' + place + '"&format=json' # Fetch the results r = requests.get(url) json = r.json() if not json['query']['results']: return "Could not find " + place + "." return json['query']['results']['place']['centroid'] def get_forecast_io_weather(self, place): if not place: raise Exception("You must provide a place name.") ll = self.latlong(place) # TODO: yeild an error if not isinstance(ll, dict): return ll # Build a forecast IO request string. TODO: Remove API key and regenerate it url = 'https://api.forecast.io/forecast/da05193c059f48ff118de841ccb7cd92/' + ll['latitude'] + "," + ll['longitude'] + "?units=uk" # Fetch the results r = requests.get(url) json = r.json() return json
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}. \ Cloud Cover: {0[cloudCover]}. Pressure: {0[pressure]}mb. Ozone: {0[ozone]}.".format(w['currently'], message.data))
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[city]}, {0[country]}: {0[condition]}, {0[temperature]}. Wind Speed: {0[wind_speed]} ({0[wind_direction]}), Wind Chill: {0[wind_chill]}. Visibility {0[visibility]}. High Temp: {0[high]}°C, Low Temp: {0[low]}°C. Sunrise: {0[sunrise]}, Sunset: {0[sunset]}.".format(w) ) else: return message.reply(data=w, text=w) @command("forecast") def forecast(self, message): """Get the 5 day forcast for a given location, from the Yahoo! Weather Service """ w = self.get_yahoo_weather(message.data) if isinstance(w, dict): return message.reply(data=w['forecast'], text="; ".join(["{0[day]}: {0[condition]}. High: {0[high]}, Low: {0[low]}.".format(x) for x in w['forecast']])) else: return message.reply(data=w, text=w) def get_yahoo_weather(self, place): if not place: raise Exception("You must provide a place name.") # Use Yahoo's yql to build the query url = 'https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in(select woeid from geo.places(1) where text="' + place + '") and u="c"&format=json' # Fetch the results r = requests.get(url) json = r.json() result = json['query']['results'] if not result: return "No weather could be found for " + place + "." # Read the pertinant parts of the result, and format them nicely. channel = result['channel'] city = channel['location']['city'] country = channel['location']['country'] region = channel['location']['region'] high = channel['item']['forecast'][0]['high'] low = channel['item']['forecast'][0]['low'] # There's a bug in the weather API where windchill is reported as "feels like" in farenheight. feelsLike = (float(channel['wind']['chill']) - 32) / 1.8 chill = feelsLike - float(channel['item']['condition']['temp']) windChill = "{0:.2f}°{1}".format(chill, channel['units']['temperature']) windDir = "{0:03d}deg".format(int(channel['wind']['direction'])) windSpeed = "{0} {1}".format(channel['wind']['speed'], channel['units']['speed']) humidity = "{0}%".format(channel['atmosphere']['humidity']) pressure = "{0}{1}".format(channel['atmosphere']['pressure'], channel['units']['pressure']) rising = channel['atmosphere']['rising'] visibility = "{0}{1}".format(channel['atmosphere']['visibility'], channel['units']['distance']) sunrise = channel['astronomy']['sunrise'] sunset = channel['astronomy']['sunset'] condition = channel['item']['condition']['text'] temperature = "{0}°{1}".format(channel['item']['condition']['temp'], channel['units']['temperature']) forecast = [] for pred in channel['item']['forecast']: c = {"day": pred['day'], "condition": pred['text'], "high": "{0}°{1}".format(pred['high'], channel['units']['temperature']), "low": "{0}°{1}".format(pred['low'], channel['units']['temperature'])} forecast.append(c) return {"city":city, "country":country, "region":region, "high":high, "low":low, "temperature": temperature, "wind_chill":windChill, "wind_direction":windDir, "wind_speed":windSpeed, "humidity":humidity, "pressure":pressure, "rising":rising, "visibility":visibility, "sunrise":sunrise, "sunset":sunset, "condition":condition, "forecast":forecast } @plugin class pollen: @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 woeid from geo.places(1) where text = "' + message.data + '"&format=json' # Fetch the results r = requests.get(yurl) json = r.json() if not json['query']['results']: return "Could not find " + place + "." woeid = json['query']['results']['place']['woeid'] print(woeid) purl = "https://pollencheck.p.mashape.com/api/1/forecasts/" + woeid headers = { "X-Mashape-Key": "O6cwEp209Jmsh614NhNE6DpXIUKhp1npOMrjsnvWzdpgHYgzob", "Accept": "application/json" } pollen_data = requests.get(purl, headers=headers) p_json = pollen_data.json() if not p_json: raise Exception("Could not get data for '" + message.data + "', try a large city.") return message.reply(data=p_json, text="Total pollen count: {0[maxLevel]}".format(p_json['periods'][0]['combined'])) @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, dict): return message.reply(data=ll, text="Latitude: {}, Longitude: {}".format(ll['latitude'], ll['longitude'])) else: return message.reply(data=ll, text=ll) @command("condition") def condition(self, message): """Get the current weather using the https://developer.forecast.io/docs/v2 API. """ if not message: raise Exception("You must provide a place name.") w = self.get_forecast_io_weather(message.data) if isinstance(w, dict): return 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}. \ Cloud Cover: {0[cloudCover]}. Pressure: {0[pressure]}mb. Ozone: {0[ozone]}.".format(w['currently'], message.data)) 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 text = "' + place + '"&format=json' # Fetch the results r = requests.get(url) json = r.json() if not json['query']['results']: return "Could not find " + place + "." return json['query']['results']['place']['centroid'] def get_forecast_io_weather(self, place): if not place: raise Exception("You must provide a place name.") ll = self.latlong(place) # TODO: yeild an error if not isinstance(ll, dict): return ll # Build a forecast IO request string. TODO: Remove API key and regenerate it url = 'https://api.forecast.io/forecast/da05193c059f48ff118de841ccb7cd92/' + ll['latitude'] + "," + ll['longitude'] + "?units=uk" # Fetch the results r = requests.get(url) json = r.json() return json
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_yahoo_weather(message.data) if isinstance(w, dict): return message.reply(data=w, text="Weather for {0[city]}, {0[country]}: {0[condition]}, {0[temperature]}. Wind Speed: {0[wind_speed]} ({0[wind_direction]}), Wind Chill: {0[wind_chill]}. Visibility {0[visibility]}. High Temp: {0[high]}°C, Low Temp: {0[low]}°C. Sunrise: {0[sunrise]}, Sunset: {0[sunset]}.".format(w) ) else: return message.reply(data=w, text=w) @command("forecast") def forecast(self, message): """Get the 5 day forcast for a given location, from the Yahoo! Weather Service """ w = self.get_yahoo_weather(message.data) if isinstance(w, dict): return message.reply(data=w['forecast'], text="; ".join(["{0[day]}: {0[condition]}. High: {0[high]}, Low: {0[low]}.".format(x) for x in w['forecast']])) else: return message.reply(data=w, text=w) def get_yahoo_weather(self, place): if not place: raise Exception("You must provide a place name.") # Use Yahoo's yql to build the query url = 'https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in(select woeid from geo.places(1) where text="' + place + '") and u="c"&format=json' # Fetch the results r = requests.get(url) json = r.json() result = json['query']['results'] if not result: return "No weather could be found for " + place + "." # Read the pertinant parts of the result, and format them nicely. channel = result['channel'] city = channel['location']['city'] country = channel['location']['country'] region = channel['location']['region'] high = channel['item']['forecast'][0]['high'] low = channel['item']['forecast'][0]['low'] # There's a bug in the weather API where windchill is reported as "feels like" in farenheight. feelsLike = (float(channel['wind']['chill']) - 32) / 1.8 chill = feelsLike - float(channel['item']['condition']['temp']) windChill = "{0:.2f}°{1}".format(chill, channel['units']['temperature']) windDir = "{0:03d}deg".format(int(channel['wind']['direction'])) windSpeed = "{0} {1}".format(channel['wind']['speed'], channel['units']['speed']) humidity = "{0}%".format(channel['atmosphere']['humidity']) pressure = "{0}{1}".format(channel['atmosphere']['pressure'], channel['units']['pressure']) rising = channel['atmosphere']['rising'] visibility = "{0}{1}".format(channel['atmosphere']['visibility'], channel['units']['distance']) sunrise = channel['astronomy']['sunrise'] sunset = channel['astronomy']['sunset'] condition = channel['item']['condition']['text'] temperature = "{0}°{1}".format(channel['item']['condition']['temp'], channel['units']['temperature']) forecast = [] for pred in channel['item']['forecast']: c = {"day": pred['day'], "condition": pred['text'], "high": "{0}°{1}".format(pred['high'], channel['units']['temperature']), "low": "{0}°{1}".format(pred['low'], channel['units']['temperature'])} forecast.append(c) return {"city":city, "country":country, "region":region, "high":high, "low":low, "temperature": temperature, "wind_chill":windChill, "wind_direction":windDir, "wind_speed":windSpeed, "humidity":humidity, "pressure":pressure, "rising":rising, "visibility":visibility, "sunrise":sunrise, "sunset":sunset, "condition":condition, "forecast":forecast } @plugin class pollen: @command("pollen") def pollen(self, message): """Get
"Accept": "application/json" } pollen_data = requests.get(purl, headers=headers) p_json = pollen_data.json() if not p_json: raise Exception("Could not get data for '" + message.data + "', try a large city.") return message.reply(data=p_json, text="Total pollen count: {0[maxLevel]}".format(p_json['periods'][0]['combined'])) @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, dict): return message.reply(data=ll, text="Latitude: {}, Longitude: {}".format(ll['latitude'], ll['longitude'])) else: return message.reply(data=ll, text=ll) @command("condition") def condition(self, message): """Get the current weather using the https://developer.forecast.io/docs/v2 API. """ if not message: raise Exception("You must provide a place name.") w = self.get_forecast_io_weather(message.data) if isinstance(w, dict): return 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}. \ Cloud Cover: {0[cloudCover]}. Pressure: {0[pressure]}mb. Ozone: {0[ozone]}.".format(w['currently'], message.data)) 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 text = "' + place + '"&format=json' # Fetch the results r = requests.get(url) json = r.json() if not json['query']['results']: return "Could not find " + place + "." return json['query']['results']['place']['centroid'] def get_forecast_io_weather(self, place): if not place: raise Exception("You must provide a place name.") ll = self.latlong(place) # TODO: yeild an error if not isinstance(ll, dict): return ll # Build a forecast IO request string. TODO: Remove API key and regenerate it url = 'https://api.forecast.io/forecast/da05193c059f48ff118de841ccb7cd92/' + ll['latitude'] + "," + ll['longitude'] + "?units=uk" # Fetch the results r = requests.get(url) json = r.json() return json
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=json' # Fetch the results r = requests.get(yurl) json = r.json() if not json['query']['results']: return "Could not find " + place + "." woeid = json['query']['results']['place']['woeid'] print(woeid) purl = "https://pollencheck.p.mashape.com/api/1/forecasts/" + woeid headers = { "X-Mashape-Key": "O6cwEp209Jmsh614NhNE6DpXIUKhp1npOMrjsnvWzdpgHYgzob",
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_yahoo_weather(message.data) if isinstance(w, dict): return message.reply(data=w, text="Weather for {0[city]}, {0[country]}: {0[condition]}, {0[temperature]}. Wind Speed: {0[wind_speed]} ({0[wind_direction]}), Wind Chill: {0[wind_chill]}. Visibility {0[visibility]}. High Temp: {0[high]}°C, Low Temp: {0[low]}°C. Sunrise: {0[sunrise]}, Sunset: {0[sunset]}.".format(w) ) else: return message.reply(data=w, text=w) @command("forecast") def forecast(self, message): """Get the 5 day forcast for a given location, from the Yahoo! Weather Service """ w = self.get_yahoo_weather(message.data) if isinstance(w, dict): return message.reply(data=w['forecast'], text="; ".join(["{0[day]}: {0[condition]}. High: {0[high]}, Low: {0[low]}.".format(x) for x in w['forecast']])) else: return message.reply(data=w, text=w) def get_yahoo_weather(self, place): if not place: raise Exception("You must provide a place name.") # Use Yahoo's yql to build the query url = 'https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in(select woeid from geo.places(1) where text="' + place + '") and u="c"&format=json' # Fetch the results r = requests.get(url) json = r.json() result = json['query']['results'] if not result: return "No weather could be found for " + place + "." # Read the pertinant parts of the result, and format them nicely. channel = result['channel'] city = channel['location']['city'] country = channel['location']['country'] region = channel['location']['region'] high = channel['item']['forecast'][0]['high'] low = channel['item']['forecast'][0]['low'] # There's a bug in the weather API where windchill is reported as "feels like" in farenheight. feelsLike = (float(channel['wind']['chill']) - 32) / 1.8 chill = feelsLike - float(channel['item']['condition']['temp']) windChill = "{0:.2f}°{1}".format(chill, channel['units']['temperature']) windDir = "{0:03d}deg".format(int(channel['wind']['direction'])) windSpeed = "{0} {1}".format(channel['wind']['speed'], channel['units']['speed']) humidity = "{0}%".format(channel['atmosphere']['humidity']) pressure = "{0}{1}".format(channel['atmosphere']['pressure'], channel['units']['pressure']) rising = channel['atmosphere']['rising'] visibility = "{0}{1}".format(channel['atmosphere']['visibility'], channel['units']['distance']) sunrise = channel['astronomy']['sunrise'] sunset = channel['astronomy']['sunset'] condition = channel['item']['condition']['text'] temperature = "{0}°{1}".format(channel['item']['condition']['temp'], channel['units']['temperature']) forecast = [] for pred in channel['item']['forecast']: c = {"day": pred['day'], "condition": pred['text'], "high": "{0}°{1}".format(pred['high'], channel['units']['temperature']), "low": "{0}°{1}".format(pred['low'], channel['units']['temperature'])} forecast.append(c) return {"city":city, "country":country, "region":region, "high":high, "low":low, "temperature": temperature, "wind_chill":windChill, "wind_direction":windDir, "wind_speed":windSpeed, "humidity":humidity, "pressure":pressure, "rising":rising, "visibility":visibility, "sunrise":sunrise, "sunset":sunset, "condition":condition, "forecast":forecast } @plugin
@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 woeid from geo.places(1) where text = "' + message.data + '"&format=json' # Fetch the results r = requests.get(yurl) json = r.json() if not json['query']['results']: return "Could not find " + place + "." woeid = json['query']['results']['place']['woeid'] print(woeid) purl = "https://pollencheck.p.mashape.com/api/1/forecasts/" + woeid headers = { "X-Mashape-Key": "O6cwEp209Jmsh614NhNE6DpXIUKhp1npOMrjsnvWzdpgHYgzob", "Accept": "application/json" } pollen_data = requests.get(purl, headers=headers) p_json = pollen_data.json() if not p_json: raise Exception("Could not get data for '" + message.data + "', try a large city.") return message.reply(data=p_json, text="Total pollen count: {0[maxLevel]}".format(p_json['periods'][0]['combined'])) @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, dict): return message.reply(data=ll, text="Latitude: {}, Longitude: {}".format(ll['latitude'], ll['longitude'])) else: return message.reply(data=ll, text=ll) @command("condition") def condition(self, message): """Get the current weather using the https://developer.forecast.io/docs/v2 API. """ if not message: raise Exception("You must provide a place name.") w = self.get_forecast_io_weather(message.data) if isinstance(w, dict): return 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}. \ Cloud Cover: {0[cloudCover]}. Pressure: {0[pressure]}mb. Ozone: {0[ozone]}.".format(w['currently'], message.data)) 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 text = "' + place + '"&format=json' # Fetch the results r = requests.get(url) json = r.json() if not json['query']['results']: return "Could not find " + place + "." return json['query']['results']['place']['centroid'] def get_forecast_io_weather(self, place): if not place: raise Exception("You must provide a place name.") ll = self.latlong(place) # TODO: yeild an error if not isinstance(ll, dict): return ll # Build a forecast IO request string. TODO: Remove API key and regenerate it url = 'https://api.forecast.io/forecast/da05193c059f48ff118de841ccb7cd92/' + ll['latitude'] + "," + ll['longitude'] + "?units=uk" # Fetch the results r = requests.get(url) json = r.json() return json
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. */ 'use strict'; /** * @class * Initializes a new instance of the A class. * @constructor * @member {string} [statusCode] * */ class A {
() { } /** * 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, serializedName: 'statusCode', type: { name: 'String' } } } } }; } } module.exports = A;
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. */ 'use strict'; /** * @class * Initializes a new instance of the A class. * @constructor * @member {string} [statusCode] * */ class A { constructor() { } /** * 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, 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) logging.getLogger("spotify.search").setLevel(logging.WARNING) logging.getLogger("spotify.session").setLevel(logging.WARNING) #Database connection - Postgres / Amazon RDS DSN = "dbname='spotlipy' user='postgres' host='127.0.0.1' password='password'" #dogstarradio search URL SEARCH_URL = 'http://www.dogstarradio.com/search_playlist.php' JUNK_INDICATORS = ['@', '#', '.com', 'Hip Hop Nation', 'SiriusXM'] #for stations numbers and names see stations.txt STATIONS = [
#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 playlist-modify-private' }
34, 44 ]
random_line_split
NodeSerializationCodes.py
, 'ContinueStmt': 72, 'WhileStmt': 73, 'DeferStmt': 74, 'ExpressionStmt': 75, 'RepeatWhileStmt': 76, 'GuardStmt': 77, 'ForInStmt': 78, 'SwitchStmt': 79, 'DoStmt': 80, 'ReturnStmt': 81, 'FallthroughStmt': 82, 'BreakStmt': 83, 'DeclarationStmt': 84, 'ThrowStmt': 85, 'IfStmt': 86, 'Decl': 87, 'Expr': 88, 'Stmt': 89, 'Type': 90, 'Pattern': 91, 'CodeBlockItem': 92, 'CodeBlock': 93, 'DeclNameArgument': 94, 'DeclNameArguments': 95, # removed: 'FunctionCallArgument': 96, 'TupleExprElement': 97, 'ArrayElement': 98, 'DictionaryElement': 99, 'ClosureCaptureItem': 100, 'ClosureCaptureSignature': 101, 'ClosureParam': 102, 'ClosureSignature': 103, 'StringSegment': 104, 'ExpressionSegment': 105, 'ObjcNamePiece': 106, 'TypeInitializerClause': 107, 'ParameterClause': 108, 'ReturnClause': 109, 'FunctionSignature': 110, 'IfConfigClause': 111, 'PoundSourceLocationArgs': 112, 'DeclModifier': 113, 'InheritedType': 114, 'TypeInheritanceClause': 115, 'MemberDeclBlock': 116, 'MemberDeclListItem': 117, 'SourceFile': 118, 'InitializerClause': 119, 'FunctionParameter': 120, 'AccessLevelModifier': 121, 'AccessPathComponent': 122, 'AccessorParameter': 123, 'AccessorBlock': 124, 'PatternBinding': 125, 'EnumCaseElement': 126, 'OperatorPrecedenceAndTypes': 127, 'PrecedenceGroupRelation': 128, 'PrecedenceGroupNameElement': 129, 'PrecedenceGroupAssignment': 130, 'PrecedenceGroupAssociativity': 131, 'Attribute': 132, 'LabeledSpecializeEntry': 133, 'ImplementsAttributeArguments': 134, 'ObjCSelectorPiece': 135, 'WhereClause': 136, 'ConditionElement': 137, 'AvailabilityCondition': 138, 'MatchingPatternCondition': 139, 'OptionalBindingCondition': 140, 'ElseIfContinuation': 141, 'ElseBlock': 142, 'SwitchCase': 143, 'SwitchDefaultLabel': 144, 'CaseItem': 145, 'SwitchCaseLabel': 146, 'CatchClause': 147, 'GenericWhereClause': 148, 'SameTypeRequirement': 149, 'GenericParameter': 150, 'GenericParameterClause': 151, 'ConformanceRequirement': 152, 'CompositionTypeElement': 153, 'TupleTypeElement': 154, 'GenericArgument': 155, 'GenericArgumentClause': 156, 'TypeAnnotation': 157, 'TuplePatternElement': 158, 'AvailabilityArgument': 159, 'AvailabilityLabeledArgument': 160, 'AvailabilityVersionRestriction': 161, 'VersionTuple': 162, 'CodeBlockItemList': 163, # removed: 'FunctionCallArgumentList': 164, 'TupleExprElementList': 165, 'ArrayElementList': 166, 'DictionaryElementList': 167, 'StringLiteralSegments': 168, 'DeclNameArgumentList': 169, 'ExprList': 170, 'ClosureCaptureItemList': 171, 'ClosureParamList': 172, 'ObjcName': 173, 'FunctionParameterList': 174, 'IfConfigClauseList': 175, 'InheritedTypeList': 176, 'MemberDeclList': 177, 'ModifierList': 178, 'AccessPath': 179, 'AccessorList': 180, 'PatternBindingList': 181, 'EnumCaseElementList': 182, 'PrecedenceGroupAttributeList': 183, 'PrecedenceGroupNameList': 184, 'TokenList': 185, 'NonEmptyTokenList': 186, 'AttributeList': 187, 'SpecializeAttributeSpecList': 188, 'ObjCSelector': 189, 'SwitchCaseList': 190, 'CatchClauseList': 191, 'CaseItemList': 192, 'ConditionElementList': 193, 'GenericRequirementList': 194, 'GenericParameterList': 195, 'CompositionTypeElementList': 196, 'TupleTypeElementList': 197, 'GenericArgumentList': 198, 'TuplePatternElementList': 199, 'AvailabilitySpecList': 200, 'UnknownPattern': 201, 'EnumCasePattern': 202, 'IsTypePattern': 203, 'OptionalPattern': 204, 'IdentifierPattern': 205, 'AsTypePattern': 206, 'TuplePattern': 207, 'WildcardPattern': 208, 'ExpressionPattern': 209, 'ValueBindingPattern': 210, 'UnknownType': 211, 'SimpleTypeIdentifier': 212, 'MemberTypeIdentifier': 213, 'ClassRestrictionType': 214, 'ArrayType': 215, 'DictionaryType': 216, 'MetatypeType': 217, 'OptionalType': 218, 'ImplicitlyUnwrappedOptionalType': 219, 'CompositionType': 220, 'TupleType': 221, 'FunctionType': 222, 'AttributedType': 223, 'YieldStmt': 224, 'YieldList': 225, 'IdentifierList': 226, 'NamedAttributeStringArgument': 227, 'DeclName': 228, 'PoundAssertStmt': 229, 'SomeType': 230, 'CustomAttribute': 231, 'GenericRequirement': 232, 'DifferentiableAttributeArguments': 233, 'DifferentiabilityParamsClause': 234, 'DifferentiabilityParams': 235, 'DifferentiabilityParamList': 236, 'DifferentiabilityParam': 237, # removed: 'DifferentiableAttributeFuncSpecifier': 238, 'FunctionDeclName': 239, 'PoundFilePathExpr': 240, 'DerivativeRegistrationAttributeArguments': 241, 'QualifiedDeclName': 242, 'CatchItem': 243, 'CatchItemList': 244, 'MultipleTrailingClosureElementList': 245, 'MultipleTrailingClosureElement': 246, 'PoundFileIDExpr': 247, 'TargetFunctionEntry': 248, } def verify_syntax_node_serialization_codes(nodes, serialization_codes): # Verify that all nodes have serialization codes for node in nodes: if not node.is_base() and node.syntax_kind not in serialization_codes: error('Node %s has no serialization code' % node.syntax_kind) # 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_serialization_code(syntax_kind):
return SYNTAX_NODE_SERIALIZATION_CODES[syntax_kind]
identifier_body
NodeSerializationCodes.py
'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'PoundSourceLocation': 8, 'ClassDecl': 9, 'StructDecl': 10, 'ProtocolDecl': 11, 'ExtensionDecl': 12, 'FunctionDecl': 13, 'InitializerDecl': 14, 'DeinitializerDecl': 15, 'SubscriptDecl': 16, 'ImportDecl': 17, 'AccessorDecl': 18, 'VariableDecl': 19, 'EnumCaseDecl': 20, 'EnumDecl': 21, 'OperatorDecl': 22, 'PrecedenceGroupDecl': 23, 'UnknownExpr': 24, 'InOutExpr': 25, 'PoundColumnExpr': 26, 'TryExpr': 27, 'AwaitExpr': 249, 'IdentifierExpr': 28, 'SuperRefExpr': 29, 'NilLiteralExpr': 30, 'DiscardAssignmentExpr': 31, 'AssignmentExpr': 32, 'SequenceExpr': 33, 'PoundLineExpr': 34, 'PoundFileExpr': 35, 'PoundFunctionExpr': 36, 'PoundDsohandleExpr': 37, 'SymbolicReferenceExpr': 38, 'PrefixOperatorExpr': 39, 'BinaryOperatorExpr': 40, 'ArrowExpr': 41, 'FloatLiteralExpr': 42, 'TupleExpr': 43, 'ArrayExpr': 44, 'DictionaryExpr': 45, 'ImplicitMemberExpr': 46, 'IntegerLiteralExpr': 47, 'StringLiteralExpr': 48, 'BooleanLiteralExpr': 49, 'TernaryExpr': 50, 'MemberAccessExpr': 51, 'DotSelfExpr': 52, 'IsExpr': 53, 'AsExpr': 54, 'TypeExpr': 55, 'ClosureExpr': 56, 'UnresolvedPatternExpr': 57, 'FunctionCallExpr': 58, 'SubscriptExpr': 59, 'OptionalChainingExpr': 60, 'ForcedValueExpr': 61, 'PostfixUnaryExpr': 62, 'SpecializeExpr': 63, 'KeyPathExpr': 65, 'KeyPathBaseExpr': 66, 'ObjcKeyPathExpr': 67, 'ObjcSelectorExpr': 68, 'EditorPlaceholderExpr': 69, 'ObjectLiteralExpr': 70, 'UnknownStmt': 71, 'ContinueStmt': 72, 'WhileStmt': 73, 'DeferStmt': 74, 'ExpressionStmt': 75, 'RepeatWhileStmt': 76, 'GuardStmt': 77, 'ForInStmt': 78, 'SwitchStmt': 79, 'DoStmt': 80, 'ReturnStmt': 81, 'FallthroughStmt': 82, 'BreakStmt': 83, 'DeclarationStmt': 84, 'ThrowStmt': 85, 'IfStmt': 86, 'Decl': 87, 'Expr': 88, 'Stmt': 89, 'Type': 90, 'Pattern': 91, 'CodeBlockItem': 92, 'CodeBlock': 93, 'DeclNameArgument': 94, 'DeclNameArguments': 95, # removed: 'FunctionCallArgument': 96, 'TupleExprElement': 97, 'ArrayElement': 98, 'DictionaryElement': 99, 'ClosureCaptureItem': 100, 'ClosureCaptureSignature': 101, 'ClosureParam': 102, 'ClosureSignature': 103, 'StringSegment': 104, 'ExpressionSegment': 105, 'ObjcNamePiece': 106, 'TypeInitializerClause': 107, 'ParameterClause': 108, 'ReturnClause': 109, 'FunctionSignature': 110, 'IfConfigClause': 111, 'PoundSourceLocationArgs': 112, 'DeclModifier': 113, 'InheritedType': 114, 'TypeInheritanceClause': 115, 'MemberDeclBlock': 116, 'MemberDeclListItem': 117, 'SourceFile': 118, 'InitializerClause': 119, 'FunctionParameter': 120, 'AccessLevelModifier': 121, 'AccessPathComponent': 122, 'AccessorParameter': 123, 'AccessorBlock': 124, 'PatternBinding': 125, 'EnumCaseElement': 126, 'OperatorPrecedenceAndTypes': 127, 'PrecedenceGroupRelation': 128, 'PrecedenceGroupNameElement': 129, 'PrecedenceGroupAssignment': 130, 'PrecedenceGroupAssociativity': 131, 'Attribute': 132, 'LabeledSpecializeEntry': 133, 'ImplementsAttributeArguments': 134, 'ObjCSelectorPiece': 135, 'WhereClause': 136, 'ConditionElement': 137, 'AvailabilityCondition': 138, 'MatchingPatternCondition': 139, 'OptionalBindingCondition': 140, 'ElseIfContinuation': 141, 'ElseBlock': 142, 'SwitchCase': 143, 'SwitchDefaultLabel': 144, 'CaseItem': 145, 'SwitchCaseLabel': 146, 'CatchClause': 147, 'GenericWhereClause': 148, 'SameTypeRequirement': 149, 'GenericParameter': 150, 'GenericParameterClause': 151, 'ConformanceRequirement': 152, 'CompositionTypeElement': 153, 'TupleTypeElement': 154, 'GenericArgument': 155, 'GenericArgumentClause': 156, 'TypeAnnotation': 157, 'TuplePatternElement': 158, 'AvailabilityArgument': 159, 'AvailabilityLabeledArgument': 160, 'AvailabilityVersionRestriction': 161, 'VersionTuple': 162, 'CodeBlockItemList': 163, # removed: 'FunctionCallArgumentList': 164, 'TupleExprElementList': 165, 'ArrayElementList': 166, 'DictionaryElementList': 167, 'StringLiteralSegments': 168, 'DeclNameArgumentList': 169, 'ExprList': 170, 'ClosureCaptureItemList': 171, 'ClosureParamList': 172, 'ObjcName': 173, 'FunctionParameterList': 174, 'IfConfigClauseList': 175, 'InheritedTypeList': 176, 'MemberDeclList': 177, 'ModifierList': 178, 'AccessPath': 179, 'AccessorList': 180, 'PatternBindingList': 181, 'EnumCaseElementList': 182, 'PrecedenceGroupAttributeList': 183, 'PrecedenceGroupNameList': 184, 'TokenList': 185, 'NonEmptyTokenList': 186, 'AttributeList': 187, 'SpecializeAttributeSpecList': 188, 'ObjCSelector': 189, 'SwitchCaseList': 190, 'CatchClauseList': 191, 'CaseItemList': 192, 'ConditionElementList': 193, 'GenericRequirementList': 194, 'GenericParameterList': 195, 'CompositionTypeElementList': 196, 'TupleTypeElementList': 197, 'GenericArgumentList': 198, 'TuplePatternElementList': 199, 'AvailabilitySpecList': 200,
random_line_split
NodeSerializationCodes.py
ObjectLiteralExpr': 70, 'UnknownStmt': 71, 'ContinueStmt': 72, 'WhileStmt': 73, 'DeferStmt': 74, 'ExpressionStmt': 75, 'RepeatWhileStmt': 76, 'GuardStmt': 77, 'ForInStmt': 78, 'SwitchStmt': 79, 'DoStmt': 80, 'ReturnStmt': 81, 'FallthroughStmt': 82, 'BreakStmt': 83, 'DeclarationStmt': 84, 'ThrowStmt': 85, 'IfStmt': 86, 'Decl': 87, 'Expr': 88, 'Stmt': 89, 'Type': 90, 'Pattern': 91, 'CodeBlockItem': 92, 'CodeBlock': 93, 'DeclNameArgument': 94, 'DeclNameArguments': 95, # removed: 'FunctionCallArgument': 96, 'TupleExprElement': 97, 'ArrayElement': 98, 'DictionaryElement': 99, 'ClosureCaptureItem': 100, 'ClosureCaptureSignature': 101, 'ClosureParam': 102, 'ClosureSignature': 103, 'StringSegment': 104, 'ExpressionSegment': 105, 'ObjcNamePiece': 106, 'TypeInitializerClause': 107, 'ParameterClause': 108, 'ReturnClause': 109, 'FunctionSignature': 110, 'IfConfigClause': 111, 'PoundSourceLocationArgs': 112, 'DeclModifier': 113, 'InheritedType': 114, 'TypeInheritanceClause': 115, 'MemberDeclBlock': 116, 'MemberDeclListItem': 117, 'SourceFile': 118, 'InitializerClause': 119, 'FunctionParameter': 120, 'AccessLevelModifier': 121, 'AccessPathComponent': 122, 'AccessorParameter': 123, 'AccessorBlock': 124, 'PatternBinding': 125, 'EnumCaseElement': 126, 'OperatorPrecedenceAndTypes': 127, 'PrecedenceGroupRelation': 128, 'PrecedenceGroupNameElement': 129, 'PrecedenceGroupAssignment': 130, 'PrecedenceGroupAssociativity': 131, 'Attribute': 132, 'LabeledSpecializeEntry': 133, 'ImplementsAttributeArguments': 134, 'ObjCSelectorPiece': 135, 'WhereClause': 136, 'ConditionElement': 137, 'AvailabilityCondition': 138, 'MatchingPatternCondition': 139, 'OptionalBindingCondition': 140, 'ElseIfContinuation': 141, 'ElseBlock': 142, 'SwitchCase': 143, 'SwitchDefaultLabel': 144, 'CaseItem': 145, 'SwitchCaseLabel': 146, 'CatchClause': 147, 'GenericWhereClause': 148, 'SameTypeRequirement': 149, 'GenericParameter': 150, 'GenericParameterClause': 151, 'ConformanceRequirement': 152, 'CompositionTypeElement': 153, 'TupleTypeElement': 154, 'GenericArgument': 155, 'GenericArgumentClause': 156, 'TypeAnnotation': 157, 'TuplePatternElement': 158, 'AvailabilityArgument': 159, 'AvailabilityLabeledArgument': 160, 'AvailabilityVersionRestriction': 161, 'VersionTuple': 162, 'CodeBlockItemList': 163, # removed: 'FunctionCallArgumentList': 164, 'TupleExprElementList': 165, 'ArrayElementList': 166, 'DictionaryElementList': 167, 'StringLiteralSegments': 168, 'DeclNameArgumentList': 169, 'ExprList': 170, 'ClosureCaptureItemList': 171, 'ClosureParamList': 172, 'ObjcName': 173, 'FunctionParameterList': 174, 'IfConfigClauseList': 175, 'InheritedTypeList': 176, 'MemberDeclList': 177, 'ModifierList': 178, 'AccessPath': 179, 'AccessorList': 180, 'PatternBindingList': 181, 'EnumCaseElementList': 182, 'PrecedenceGroupAttributeList': 183, 'PrecedenceGroupNameList': 184, 'TokenList': 185, 'NonEmptyTokenList': 186, 'AttributeList': 187, 'SpecializeAttributeSpecList': 188, 'ObjCSelector': 189, 'SwitchCaseList': 190, 'CatchClauseList': 191, 'CaseItemList': 192, 'ConditionElementList': 193, 'GenericRequirementList': 194, 'GenericParameterList': 195, 'CompositionTypeElementList': 196, 'TupleTypeElementList': 197, 'GenericArgumentList': 198, 'TuplePatternElementList': 199, 'AvailabilitySpecList': 200, 'UnknownPattern': 201, 'EnumCasePattern': 202, 'IsTypePattern': 203, 'OptionalPattern': 204, 'IdentifierPattern': 205, 'AsTypePattern': 206, 'TuplePattern': 207, 'WildcardPattern': 208, 'ExpressionPattern': 209, 'ValueBindingPattern': 210, 'UnknownType': 211, 'SimpleTypeIdentifier': 212, 'MemberTypeIdentifier': 213, 'ClassRestrictionType': 214, 'ArrayType': 215, 'DictionaryType': 216, 'MetatypeType': 217, 'OptionalType': 218, 'ImplicitlyUnwrappedOptionalType': 219, 'CompositionType': 220, 'TupleType': 221, 'FunctionType': 222, 'AttributedType': 223, 'YieldStmt': 224, 'YieldList': 225, 'IdentifierList': 226, 'NamedAttributeStringArgument': 227, 'DeclName': 228, 'PoundAssertStmt': 229, 'SomeType': 230, 'CustomAttribute': 231, 'GenericRequirement': 232, 'DifferentiableAttributeArguments': 233, 'DifferentiabilityParamsClause': 234, 'DifferentiabilityParams': 235, 'DifferentiabilityParamList': 236, 'DifferentiabilityParam': 237, # removed: 'DifferentiableAttributeFuncSpecifier': 238, 'FunctionDeclName': 239, 'PoundFilePathExpr': 240, 'DerivativeRegistrationAttributeArguments': 241, 'QualifiedDeclName': 242, 'CatchItem': 243, 'CatchItemList': 244, 'MultipleTrailingClosureElementList': 245, 'MultipleTrailingClosureElement': 246, 'PoundFileIDExpr': 247, 'TargetFunctionEntry': 248, } def verify_syntax_node_serialization_codes(nodes, serialization_codes): # Verify that all nodes have serialization codes for node in nodes: if not node.is_base() and node.syntax_kind not in serialization_codes: error('Node %s has no serialization code' % node.syntax_kind) # 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_serialization_code
identifier_name
NodeSerializationCodes.py
Expr': 63, 'KeyPathExpr': 65, 'KeyPathBaseExpr': 66, 'ObjcKeyPathExpr': 67, 'ObjcSelectorExpr': 68, 'EditorPlaceholderExpr': 69, 'ObjectLiteralExpr': 70, 'UnknownStmt': 71, 'ContinueStmt': 72, 'WhileStmt': 73, 'DeferStmt': 74, 'ExpressionStmt': 75, 'RepeatWhileStmt': 76, 'GuardStmt': 77, 'ForInStmt': 78, 'SwitchStmt': 79, 'DoStmt': 80, 'ReturnStmt': 81, 'FallthroughStmt': 82, 'BreakStmt': 83, 'DeclarationStmt': 84, 'ThrowStmt': 85, 'IfStmt': 86, 'Decl': 87, 'Expr': 88, 'Stmt': 89, 'Type': 90, 'Pattern': 91, 'CodeBlockItem': 92, 'CodeBlock': 93, 'DeclNameArgument': 94, 'DeclNameArguments': 95, # removed: 'FunctionCallArgument': 96, 'TupleExprElement': 97, 'ArrayElement': 98, 'DictionaryElement': 99, 'ClosureCaptureItem': 100, 'ClosureCaptureSignature': 101, 'ClosureParam': 102, 'ClosureSignature': 103, 'StringSegment': 104, 'ExpressionSegment': 105, 'ObjcNamePiece': 106, 'TypeInitializerClause': 107, 'ParameterClause': 108, 'ReturnClause': 109, 'FunctionSignature': 110, 'IfConfigClause': 111, 'PoundSourceLocationArgs': 112, 'DeclModifier': 113, 'InheritedType': 114, 'TypeInheritanceClause': 115, 'MemberDeclBlock': 116, 'MemberDeclListItem': 117, 'SourceFile': 118, 'InitializerClause': 119, 'FunctionParameter': 120, 'AccessLevelModifier': 121, 'AccessPathComponent': 122, 'AccessorParameter': 123, 'AccessorBlock': 124, 'PatternBinding': 125, 'EnumCaseElement': 126, 'OperatorPrecedenceAndTypes': 127, 'PrecedenceGroupRelation': 128, 'PrecedenceGroupNameElement': 129, 'PrecedenceGroupAssignment': 130, 'PrecedenceGroupAssociativity': 131, 'Attribute': 132, 'LabeledSpecializeEntry': 133, 'ImplementsAttributeArguments': 134, 'ObjCSelectorPiece': 135, 'WhereClause': 136, 'ConditionElement': 137, 'AvailabilityCondition': 138, 'MatchingPatternCondition': 139, 'OptionalBindingCondition': 140, 'ElseIfContinuation': 141, 'ElseBlock': 142, 'SwitchCase': 143, 'SwitchDefaultLabel': 144, 'CaseItem': 145, 'SwitchCaseLabel': 146, 'CatchClause': 147, 'GenericWhereClause': 148, 'SameTypeRequirement': 149, 'GenericParameter': 150, 'GenericParameterClause': 151, 'ConformanceRequirement': 152, 'CompositionTypeElement': 153, 'TupleTypeElement': 154, 'GenericArgument': 155, 'GenericArgumentClause': 156, 'TypeAnnotation': 157, 'TuplePatternElement': 158, 'AvailabilityArgument': 159, 'AvailabilityLabeledArgument': 160, 'AvailabilityVersionRestriction': 161, 'VersionTuple': 162, 'CodeBlockItemList': 163, # removed: 'FunctionCallArgumentList': 164, 'TupleExprElementList': 165, 'ArrayElementList': 166, 'DictionaryElementList': 167, 'StringLiteralSegments': 168, 'DeclNameArgumentList': 169, 'ExprList': 170, 'ClosureCaptureItemList': 171, 'ClosureParamList': 172, 'ObjcName': 173, 'FunctionParameterList': 174, 'IfConfigClauseList': 175, 'InheritedTypeList': 176, 'MemberDeclList': 177, 'ModifierList': 178, 'AccessPath': 179, 'AccessorList': 180, 'PatternBindingList': 181, 'EnumCaseElementList': 182, 'PrecedenceGroupAttributeList': 183, 'PrecedenceGroupNameList': 184, 'TokenList': 185, 'NonEmptyTokenList': 186, 'AttributeList': 187, 'SpecializeAttributeSpecList': 188, 'ObjCSelector': 189, 'SwitchCaseList': 190, 'CatchClauseList': 191, 'CaseItemList': 192, 'ConditionElementList': 193, 'GenericRequirementList': 194, 'GenericParameterList': 195, 'CompositionTypeElementList': 196, 'TupleTypeElementList': 197, 'GenericArgumentList': 198, 'TuplePatternElementList': 199, 'AvailabilitySpecList': 200, 'UnknownPattern': 201, 'EnumCasePattern': 202, 'IsTypePattern': 203, 'OptionalPattern': 204, 'IdentifierPattern': 205, 'AsTypePattern': 206, 'TuplePattern': 207, 'WildcardPattern': 208, 'ExpressionPattern': 209, 'ValueBindingPattern': 210, 'UnknownType': 211, 'SimpleTypeIdentifier': 212, 'MemberTypeIdentifier': 213, 'ClassRestrictionType': 214, 'ArrayType': 215, 'DictionaryType': 216, 'MetatypeType': 217, 'OptionalType': 218, 'ImplicitlyUnwrappedOptionalType': 219, 'CompositionType': 220, 'TupleType': 221, 'FunctionType': 222, 'AttributedType': 223, 'YieldStmt': 224, 'YieldList': 225, 'IdentifierList': 226, 'NamedAttributeStringArgument': 227, 'DeclName': 228, 'PoundAssertStmt': 229, 'SomeType': 230, 'CustomAttribute': 231, 'GenericRequirement': 232, 'DifferentiableAttributeArguments': 233, 'DifferentiabilityParamsClause': 234, 'DifferentiabilityParams': 235, 'DifferentiabilityParamList': 236, 'DifferentiabilityParam': 237, # removed: 'DifferentiableAttributeFuncSpecifier': 238, 'FunctionDeclName': 239, 'PoundFilePathExpr': 240, 'DerivativeRegistrationAttributeArguments': 241, 'QualifiedDeclName': 242, 'CatchItem': 243, 'CatchItemList': 244, 'MultipleTrailingClosureElementList': 245, 'MultipleTrailingClosureElement': 246, 'PoundFileIDExpr': 247, 'TargetFunctionEntry': 248, } def verify_syntax_node_serialization_codes(nodes, serialization_codes): # Verify that all nodes have serialization codes for node in nodes:
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 probabilistic factor graphs. extern crate dot; mod render; pub mod variable; pub mod factor; pub mod tree; use std::collections::HashMap; use std::collections::VecDeque; use std::io::Write; pub use variable::{Variable, DiscreteVariable}; pub use factor::Factor; pub use tree::{SpanningTree, TreeNode}; type PotentialFunc = fn(&[u32]) -> i32; /// Trait representing a generic item stored in the factor graph. pub trait FactorGraphItem : std::fmt::Debug { /// Get the name of this item. fn get_name(&self) -> String; /// Get this item's id. fn get_id(&self) -> u32; /// Return whether the item is a factor. fn is_factor(&self) -> bool; /// Add this node to the spanning tree. fn add_to_tree(&self, parent_id: u32, tree: &mut SpanningTree); } /// Struct representing the full factor graph. #[derive(Debug)] pub struct FactorGraph { variables: HashMap<String, Box<Variable>>, factors: Vec<Factor>, next_id: u32, all_names: Vec<String>, is_factor: Vec<bool>, } impl FactorGraph { /// Create an empty FactorGraph pub fn new() -> FactorGraph { FactorGraph { variables: HashMap::new(), factors: vec!(), next_id: 0, all_names: vec!(), is_factor: vec!(), } } /// Add a new variable with the specified name to the factor graph. pub fn add_discrete_var<T : std::fmt::Debug + Clone + 'static>(&mut self, name: &str, val_names: Vec<T>) { let new_var = DiscreteVariable::new(self.next_id, name, val_names.clone()); self.variables.insert(String::from(name), Box::new(new_var)); self.all_names.insert(self.next_id as usize, String::from(name)); self.is_factor.insert(self.next_id as usize, false); self.next_id += 1; } /// Add a new factor with the specified variables to the factor graph. pub fn add_factor<T: std::fmt::Debug + 'static>(&mut self, variables: Vec<String>, func: PotentialFunc)
/// 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 from the current factor graph with the specified root variable. pub fn make_spanning_tree(&self, var: &str) -> SpanningTree { let root = match self.variables.get(var) { Some(v) => v, None => panic!("Root variable not found") }; let mut spanning_tree = SpanningTree::new(root.get_id(), &root.get_name(), self.variables.values().len()); let mut var_iteration = true; let mut var_queue: VecDeque<&Box<Variable>> = VecDeque::new(); let mut factor_queue: VecDeque<&Factor> = VecDeque::new(); var_queue.push_back(root); // BFS through the graph, recording the spanning tree. while !var_queue.is_empty() || !factor_queue.is_empty() { if var_iteration { let node = match var_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for factor in node.get_factors() { if !spanning_tree.has_node(factor.get_id()) { spanning_tree.add_child((*node).get_id(), factor.get_id(), &factor.get_name()); if factor_queue.iter().filter(|x| (*x).get_id() == factor.get_id()).count() == 0 { factor_queue.push_back(factor); } } } if var_queue.is_empty() { var_iteration = false; } } else { let node = match factor_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for var_name in node.get_variables() { let var = match self.variables.get(var_name) { Some(x) => x, None => panic!("Could not find variable with name {}", var_name) }; if !spanning_tree.has_node(var.get_id()) { spanning_tree.add_child(node.get_id(), var.get_id(), &var.get_name()); if var_queue.iter().filter(|x| x.get_id() == var.get_id()).count() == 0 { var_queue.push_back(var); } } } if factor_queue.is_empty() { var_iteration = true; } } } spanning_tree } /// Render a spanning tree for the factor graph to the input file, starting from the input variable. pub fn render_spanning_tree_to<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() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("second")), dummy_func); } #[test] fn factor_is_added_to_var() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("first")), dummy_func); assert_eq!(graph.variables.get("first").unwrap().get_factors()[0].get_variables(), graph.factors[0].get_variables()) } }
{ 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.", var) } } self.factors.push(Factor::new(self.next_id, variables.clone(), func)); self.all_names.insert(self.next_id as usize, String::from(format!("factor<{:?}>", variables.clone()))); self.is_factor.insert(self.next_id as usize, true); self.next_id += 1; }
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 probabilistic factor graphs. extern crate dot; mod render; pub mod variable; pub mod factor; pub mod tree; use std::collections::HashMap; use std::collections::VecDeque; use std::io::Write; pub use variable::{Variable, DiscreteVariable}; pub use factor::Factor; pub use tree::{SpanningTree, TreeNode}; type PotentialFunc = fn(&[u32]) -> i32; /// Trait representing a generic item stored in the factor graph. pub trait FactorGraphItem : std::fmt::Debug { /// Get the name of this item. fn get_name(&self) -> String; /// Get this item's id. fn get_id(&self) -> u32; /// Return whether the item is a factor. fn is_factor(&self) -> bool; /// Add this node to the spanning tree. fn add_to_tree(&self, parent_id: u32, tree: &mut SpanningTree); } /// Struct representing the full factor graph. #[derive(Debug)] pub struct FactorGraph { variables: HashMap<String, Box<Variable>>, factors: Vec<Factor>, next_id: u32, all_names: Vec<String>, is_factor: Vec<bool>, } impl FactorGraph { /// Create an empty FactorGraph pub fn new() -> FactorGraph { FactorGraph { variables: HashMap::new(), factors: vec!(), next_id: 0, all_names: vec!(), is_factor: vec!(), } } /// Add a new variable with the specified name to the factor graph. pub fn add_discrete_var<T : std::fmt::Debug + Clone + 'static>(&mut self, name: &str, val_names: Vec<T>) { let new_var = DiscreteVariable::new(self.next_id, name, val_names.clone()); self.variables.insert(String::from(name), Box::new(new_var)); self.all_names.insert(self.next_id as usize, String::from(name)); self.is_factor.insert(self.next_id as usize, false); self.next_id += 1; } /// Add a new factor with the specified variables to the factor graph. pub fn add_factor<T: std::fmt::Debug + 'static>(&mut self, variables: Vec<String>, func: PotentialFunc) { 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.", var) } } self.factors.push(Factor::new(self.next_id, variables.clone(), func)); self.all_names.insert(self.next_id as usize, String::from(format!("factor<{:?}>", variables.clone()))); self.is_factor.insert(self.next_id as usize, true); self.next_id += 1; } /// 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 from the current factor graph with the specified root variable. pub fn make_spanning_tree(&self, var: &str) -> SpanningTree { let root = match self.variables.get(var) { Some(v) => v, None => panic!("Root variable not found") }; let mut spanning_tree = SpanningTree::new(root.get_id(), &root.get_name(), self.variables.values().len()); let mut var_iteration = true; let mut var_queue: VecDeque<&Box<Variable>> = VecDeque::new(); let mut factor_queue: VecDeque<&Factor> = VecDeque::new(); var_queue.push_back(root); // BFS through the graph, recording the spanning tree. while !var_queue.is_empty() || !factor_queue.is_empty() { if var_iteration { let node = match var_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for factor in node.get_factors() { if !spanning_tree.has_node(factor.get_id()) { spanning_tree.add_child((*node).get_id(), factor.get_id(), &factor.get_name()); if factor_queue.iter().filter(|x| (*x).get_id() == factor.get_id()).count() == 0 { factor_queue.push_back(factor); } } } if var_queue.is_empty() { var_iteration = false; } } else { let node = match factor_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for var_name in node.get_variables() { let var = match self.variables.get(var_name) { Some(x) => x, None => panic!("Could not find variable with name {}", var_name) }; if !spanning_tree.has_node(var.get_id()) { spanning_tree.add_child(node.get_id(), var.get_id(), &var.get_name()); if var_queue.iter().filter(|x| x.get_id() == var.get_id()).count() == 0 { var_queue.push_back(var); } } } if factor_queue.is_empty() { var_iteration = true; } } } spanning_tree } /// Render a spanning tree for the factor graph to the input file, starting from the input variable. pub fn render_spanning_tree_to<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() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("second")), dummy_func); } #[test] fn factor_is_added_to_var() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("first")), dummy_func); assert_eq!(graph.variables.get("first").unwrap().get_factors()[0].get_variables(), graph.factors[0].get_variables()) } }
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 probabilistic factor graphs. extern crate dot; mod render; pub mod variable; pub mod factor; pub mod tree; use std::collections::HashMap; use std::collections::VecDeque; use std::io::Write; pub use variable::{Variable, DiscreteVariable}; pub use factor::Factor; pub use tree::{SpanningTree, TreeNode}; type PotentialFunc = fn(&[u32]) -> i32; /// Trait representing a generic item stored in the factor graph. pub trait FactorGraphItem : std::fmt::Debug { /// Get the name of this item. fn get_name(&self) -> String; /// Get this item's id. fn get_id(&self) -> u32; /// Return whether the item is a factor. fn is_factor(&self) -> bool; /// Add this node to the spanning tree. fn add_to_tree(&self, parent_id: u32, tree: &mut SpanningTree); } /// Struct representing the full factor graph. #[derive(Debug)] pub struct FactorGraph { variables: HashMap<String, Box<Variable>>, factors: Vec<Factor>, next_id: u32, all_names: Vec<String>, is_factor: Vec<bool>, } impl FactorGraph { /// Create an empty FactorGraph pub fn new() -> FactorGraph { FactorGraph { variables: HashMap::new(), factors: vec!(), next_id: 0, all_names: vec!(), is_factor: vec!(), } } /// Add a new variable with the specified name to the factor graph. pub fn add_discrete_var<T : std::fmt::Debug + Clone + 'static>(&mut self, name: &str, val_names: Vec<T>) { let new_var = DiscreteVariable::new(self.next_id, name, val_names.clone()); self.variables.insert(String::from(name), Box::new(new_var)); self.all_names.insert(self.next_id as usize, String::from(name)); self.is_factor.insert(self.next_id as usize, false); self.next_id += 1; } /// Add a new factor with the specified variables to the factor graph. pub fn add_factor<T: std::fmt::Debug + 'static>(&mut self, variables: Vec<String>, func: PotentialFunc) { 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.", var) } } self.factors.push(Factor::new(self.next_id, variables.clone(), func)); self.all_names.insert(self.next_id as usize, String::from(format!("factor<{:?}>", variables.clone()))); self.is_factor.insert(self.next_id as usize, true); self.next_id += 1; } /// 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 from the current factor graph with the specified root variable. pub fn make_spanning_tree(&self, var: &str) -> SpanningTree { let root = match self.variables.get(var) { Some(v) => v, None => panic!("Root variable not found") }; let mut spanning_tree = SpanningTree::new(root.get_id(), &root.get_name(), self.variables.values().len()); let mut var_iteration = true; let mut var_queue: VecDeque<&Box<Variable>> = VecDeque::new(); let mut factor_queue: VecDeque<&Factor> = VecDeque::new(); var_queue.push_back(root); // BFS through the graph, recording the spanning tree. while !var_queue.is_empty() || !factor_queue.is_empty() { if var_iteration { let node = match var_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for factor in node.get_factors() { if !spanning_tree.has_node(factor.get_id()) { spanning_tree.add_child((*node).get_id(), factor.get_id(), &factor.get_name()); if factor_queue.iter().filter(|x| (*x).get_id() == factor.get_id()).count() == 0 { factor_queue.push_back(factor); } } } if var_queue.is_empty() { var_iteration = false; } } else { let node = match factor_queue.pop_front() { Some(x) => x, None => panic!("Queue is unexpectedly empty") }; for var_name in node.get_variables() { let var = match self.variables.get(var_name) { Some(x) => x, None => panic!("Could not find variable with name {}", var_name) }; if !spanning_tree.has_node(var.get_id()) { spanning_tree.add_child(node.get_id(), var.get_id(), &var.get_name()); if var_queue.iter().filter(|x| x.get_id() == var.get_id()).count() == 0 { var_queue.push_back(var); } } } if factor_queue.is_empty() { var_iteration = true; } } } spanning_tree } /// Render a spanning tree for the factor graph to the input file, starting from the input variable. pub fn
<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() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("second")), dummy_func); } #[test] fn factor_is_added_to_var() { let mut graph = FactorGraph::new(); graph.add_discrete_var("first", vec![1, 2]); graph.add_factor::<i32>(vec!(String::from("first")), dummy_func); assert_eq!(graph.variables.get("first").unwrap().get_factors()[0].get_variables(), graph.factors[0].get_variables()) } }
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.thumbnail'), url(r'^render/(?P<photo_id>\d+)/scale/(?P<request_width>\d+)/$', 'render.views.scale'), url(r'^$', 'browser.views.tag_list'), url(r'^tag/(?P<tag_id>\d+)/$', 'browser.views.tag'), url(r'^photo/(?P<photo_id>\d+)/$', 'browser.views.photo'), url(r'^time/$', 'browser.views.time'), url(r'^time/month/(?P<year_int>\d+)-(?P<month_int>\d+)/$', 'browser.views.month'), url(r'^hack/tag-best-2011/(?P<photo_id>\d+)/', 'browser.views.hack_best_2011'),
# 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_browser.views.home', name='home'),
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',['encodingutils.h',['../encodingutils_8h.html',1,'']]],
['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',['../environment_8h.html',1,'']]], ['eulerian_5fpath_2eh_9',['eulerian_path.h',['../eulerian__path_8h.html',1,'']]],
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.noConflict(); (function($,PLUGIN_ID){ "use strict"; var vars={ fieldinfos:{} }; var functions={ fieldsort:function(layout){ var codes=[]; $.each(layout,function(index,values){ switch (values.type) { case 'ROW': $.each(values.fields,function(index,values){ /* exclude spacer */ if (!values.elementId) codes.push(values.code); }); break; case 'GROUP': $.merge(codes,functions.fieldsort(values.layout)); break; } }); return codes; } }; /*--------------------------------------------------------------- initialize fields ---------------------------------------------------------------*/ kintone.api(kintone.api.url('/k/v1/app/form/layout',true),'GET',{app:kintone.app.getId()},function(resp){ var sorted=functions.fieldsort(resp.layout); /* get fieldinfo */ kintone.api(kintone.api.url('/k/v1/app/form/fields',true),'GET',{app:kintone.app.getId()},function(resp){ var config=kintone.plugin.app.getConfig(PLUGIN_ID); vars.fieldinfos=resp.properties; $.each(sorted,function(index){ if (sorted[index] in vars.fieldinfos) { var fieldinfo=vars.fieldinfos[sorted[index]]; /* check field type */ switch (fieldinfo.type) { case 'NUMBER': /* exclude lookup */ if (!fieldinfo.lookup) $('select#id').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label)); break; case 'SINGLE_LINE_TEXT': /* exclude lookup */ if (!fieldinfo.lookup)
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#freeeappid').val(config['freeeappid']); $('input#freeesecret').val(config['freeesecret']); } },function(error){}); },function(error){}); /*--------------------------------------------------------------- button events ---------------------------------------------------------------*/ $('button#submit').on('click',function(e){ var config=[]; /* check values */ if (!$('input#freeeappid').val()) { swal('Error!','FreeeAppIDを入力して下さい。','error'); return; } if (!$('input#freeesecret').val()) { swal('Error!','FreeeSecretを入力して下さい。','error'); return; } if (!$('select#id').val()) { swal('Error!','部門IDフィールドを選択して下さい。','error'); return; } if (!$('select#name').val()) { swal('Error!','部門名フィールドを選択して下さい。','error'); return; } /* setup config */ config['id']=$('select#id').val(); config['name']=$('select#name').val(); config['shortcut1']=$('select#shortcut1').val(); config['shortcut2']=$('select#shortcut2').val(); config['freeeappid']=$('input#freeeappid').val(); config['freeesecret']=$('input#freeesecret').val(); /* save config */ kintone.plugin.app.setConfig(config); }); $('button#cancel').on('click',function(e){ history.back(); }); })(jQuery,kintone.$PLUGIN_ID);
{ $('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.noConflict(); (function($,PLUGIN_ID){ "use strict"; var vars={ fieldinfos:{} }; var functions={ fieldsort:function(layout){ var codes=[]; $.each(layout,function(index,values){ switch (values.type) { case 'ROW': $.each(values.fields,function(index,values){
$.merge(codes,functions.fieldsort(values.layout)); break; } }); return codes; } }; /*--------------------------------------------------------------- initialize fields ---------------------------------------------------------------*/ kintone.api(kintone.api.url('/k/v1/app/form/layout',true),'GET',{app:kintone.app.getId()},function(resp){ var sorted=functions.fieldsort(resp.layout); /* get fieldinfo */ kintone.api(kintone.api.url('/k/v1/app/form/fields',true),'GET',{app:kintone.app.getId()},function(resp){ var config=kintone.plugin.app.getConfig(PLUGIN_ID); vars.fieldinfos=resp.properties; $.each(sorted,function(index){ if (sorted[index] in vars.fieldinfos) { var fieldinfo=vars.fieldinfos[sorted[index]]; /* check field type */ switch (fieldinfo.type) { case 'NUMBER': /* exclude lookup */ if (!fieldinfo.lookup) $('select#id').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label)); break; case 'SINGLE_LINE_TEXT': /* exclude lookup */ if (!fieldinfo.lookup) { $('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)); } 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#freeeappid').val(config['freeeappid']); $('input#freeesecret').val(config['freeesecret']); } },function(error){}); },function(error){}); /*--------------------------------------------------------------- button events ---------------------------------------------------------------*/ $('button#submit').on('click',function(e){ var config=[]; /* check values */ if (!$('input#freeeappid').val()) { swal('Error!','FreeeAppIDを入力して下さい。','error'); return; } if (!$('input#freeesecret').val()) { swal('Error!','FreeeSecretを入力して下さい。','error'); return; } if (!$('select#id').val()) { swal('Error!','部門IDフィールドを選択して下さい。','error'); return; } if (!$('select#name').val()) { swal('Error!','部門名フィールドを選択して下さい。','error'); return; } /* setup config */ config['id']=$('select#id').val(); config['name']=$('select#name').val(); config['shortcut1']=$('select#shortcut1').val(); config['shortcut2']=$('select#shortcut2').val(); config['freeeappid']=$('input#freeeappid').val(); config['freeesecret']=$('input#freeesecret').val(); /* save config */ kintone.plugin.app.setConfig(config); }); $('button#cancel').on('click',function(e){ history.back(); }); })(jQuery,kintone.$PLUGIN_ID);
/* 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 <[email protected]> # # 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 published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. #
# 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/>. # ---------------------------------------------------------------------------- import logging,sys logger = logging.getLogger() X10Checkers = { 'RF' : 'x10chk(args)' , 'PL' : 'x10chk(args)' , } X10Encoders = { 'RF' : ('', 'x10rf2hex(args)', '') , 'PL' : ('', 'x10pl2hex(args)', '') , }
# 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({ templateUrl: './support.component.html' }) export class SupportComponent { model = { message: null }; submitted = false; constructor( private auth: AuthService, private api: ApiService, private location: Location, private toasterService: ToasterService, private spinner: SpinnerService )
/** * send() function * Send email */ send(): void { let message = { text: this.model.message, to: "[email protected]", subject: "Prode de Amigos | Soporte" }; this.spinner.show(); this.api.sendMessage(this.auth.user.id, message).subscribe( data => { this.toasterService.pop('success', 'OK', 'Mensaje enviado.'); this.spinner.hide(); this.submitted = true; }, error => { console.log(<any>error); this.toasterService.pop('error', 'Error', 'Hubo un error. Intenta mas tarde.'); this.spinner.hide(); } ); return; } /** * cancel() function */ cancel(): void { this.location.back(); } }
{ }
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({ templateUrl: './support.component.html' }) export class SupportComponent { model = { message: null }; submitted = false; constructor( private auth: AuthService,
private spinner: SpinnerService ) { } /** * send() function * Send email */ send(): void { let message = { text: this.model.message, to: "[email protected]", subject: "Prode de Amigos | Soporte" }; this.spinner.show(); this.api.sendMessage(this.auth.user.id, message).subscribe( data => { this.toasterService.pop('success', 'OK', 'Mensaje enviado.'); this.spinner.hide(); this.submitted = true; }, error => { console.log(<any>error); this.toasterService.pop('error', 'Error', 'Hubo un error. Intenta mas tarde.'); this.spinner.hide(); } ); return; } /** * cancel() function */ cancel(): void { this.location.back(); } }
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({ templateUrl: './support.component.html' }) export class SupportComponent { model = { message: null }; submitted = false;
( private auth: AuthService, private api: ApiService, private location: Location, private toasterService: ToasterService, private spinner: SpinnerService ) { } /** * send() function * Send email */ send(): void { let message = { text: this.model.message, to: "[email protected]", subject: "Prode de Amigos | Soporte" }; this.spinner.show(); this.api.sendMessage(this.auth.user.id, message).subscribe( data => { this.toasterService.pop('success', 'OK', 'Mensaje enviado.'); this.spinner.hide(); this.submitted = true; }, error => { console.log(<any>error); this.toasterService.pop('error', 'Error', 'Hubo un error. Intenta mas tarde.'); this.spinner.hide(); } ); return; } /** * cancel() function */ cancel(): void { this.location.back(); } }
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', 'h1': 'test1'}} @unittest.skipUnless(etree, 'lxml not installed') class XMLTestCase(TestCase): def test_pretty_xml(self):
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 test_pretty_xml(self): self.assertEqual(pretty_xml(XML_DATA), XML_PRETTY) 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)
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', 'h1': 'test1'}} @unittest.skipUnless(etree, 'lxml not installed') class XMLTestCase(TestCase): def test_pretty_xml(self): self.assertEqual(pretty_xml(XML_DATA), XML_PRETTY) def test_element_to_dict(self): self.assertEqual(element_to_dict(etree.XML(XML_DATA)), XML_DICT) def
(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, { 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 { 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: Expression + Copy> QuerySource for Aliased<'a, T> { type FromClause = InfixNode<'static, T, Identifier<'a>>; fn from_clause(&self) -> Self::FromClause { InfixNode::new(self.expr, Identifier(self.alias), " ") } } impl<'a, T> NonAggregate for Aliased<'a, T> where Aliased<'a, 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> { 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, { type SqlType = T::SqlType; }
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: Expression + Copy> QuerySource for Aliased<'a, T> { type FromClause = InfixNode<'static, T, Identifier<'a>>; fn from_clause(&self) -> Self::FromClause { InfixNode::new(self.expr, Identifier(self.alias), " ") } } impl<'a, T> NonAggregate for Aliased<'a, T> where Aliased<'a, T>: Expression { }
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 fn new(expr: Expr, alias: &'a str) -> Self
} 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 { 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: Expression + Copy> QuerySource for Aliased<'a, T> { type FromClause = InfixNode<'static, T, Identifier<'a>>; fn from_clause(&self) -> Self::FromClause { InfixNode::new(self.expr, Identifier(self.alias), " ") } } impl<'a, T> NonAggregate for Aliased<'a, T> where Aliased<'a, T>: Expression { }
{ Aliased { expr: expr, alias: alias, } }
identifier_body
font.rs
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 std::mem; use std::rc::Rc; use std::slice; use std::sync::Arc; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use util::cache::HashCache; use font_template::FontTemplateDescriptor; use platform::font::{FontHandle, FontTable}; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use text::Shaper; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use util::geometry::Au; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry, Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32, FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc = "Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc = "Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc = "Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04, #[doc = "Text direction is right-to-left."] const RTL_FLAG = 0x08, } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct
{ /// 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` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; if let Some(glyphs) = self.shape_cache.find(&lookup_key) { return glyphs.clone(); } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG), options.flags.contains(RTL_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper if let Some(ref mut shaper) = self.shaper { shaper.set_options(options); return shaper } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: SmallVec<[Rc<RefCell<Font>>; 8]>, } impl FontGroup { pub fn new(fonts: SmallVec<[Rc<RefCell<Font>>; 8]>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } 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+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box.
ShapingOptions
identifier_name
font.rs
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 std::mem; use std::rc::Rc; use std::slice; use std::sync::Arc; use style::computed_values::{font_stretch, font_variant, font_weight}; use style::properties::style_structs::Font as FontStyle; use util::cache::HashCache; use font_template::FontTemplateDescriptor; use platform::font::{FontHandle, FontTable}; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use text::Shaper; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use util::geometry::Au; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self,()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let pointer = mem::transmute::<&u32, *const u8>(self); let mut bytes = slice::from_raw_parts(pointer, 4).to_vec(); bytes.reverse(); String::from_utf8_unchecked(bytes) } } } pub trait FontTableMethods { fn with_buffer<F>(&self, F) where F: FnOnce(*const u8, usize); } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } pub type SpecifiedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, pub shape_cache: HashCache<ShapeCacheEntry, Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32, FractionalPixel>, } bitflags! { flags ShapingFlags: u8 { #[doc = "Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, #[doc = "Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, #[doc = "Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04, #[doc = "Text direction is right-to-left."] const RTL_FLAG = 0x08, } } /// Various options that control text shaping. #[derive(Clone, Eq, PartialEq, Hash, Copy)] pub struct ShapingOptions { /// 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` property. pub word_spacing: Au, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Eq, PartialEq, Hash)] pub struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { self.make_shaper(options); //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef let shaper = &self.shaper; let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: options.clone(), }; if let Some(glyphs) = self.shape_cache.find(&lookup_key) { return glyphs.clone(); } let mut glyphs = GlyphStore::new(text.chars().count(), options.flags.contains(IS_WHITESPACE_SHAPING_FLAG), options.flags.contains(RTL_FLAG)); shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); let glyphs = Arc::new(glyphs); self.shape_cache.insert(ShapeCacheEntry { text: text.to_owned(), options: *options, }, glyphs.clone()); glyphs } fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper { // fast path: already created a shaper if let Some(ref mut shaper) = self.shaper { shaper.set_options(options); return shaper } let shaper = Shaper::new(self, options); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: SmallVec<[Rc<RefCell<Font>>; 8]>, } impl FontGroup { pub fn new(fonts: SmallVec<[Rc<RefCell<Font>>; 8]>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero
} 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+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box.
// 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_Position.xy = gl_Position.xy + posoffset / window_size; gl_PointSize = point_size; flat_text_map = text_map; """ def FS(background_transparent=True): if background_transparent: background_transparent_shader = "letter_alpha" else: background_transparent_shader = "1." fs = """ // relative coordinates of the pixel within the sprite (in [0,1]) float x = gl_PointCoord.x; float y = gl_PointCoord.y; // size of the corresponding character float w = flat_text_map.z; float h = flat_text_map.w; // display the character at the left of the sprite float delta = h / w; x = delta * x; if ((x >= 0) && (x <= 1)) { // coordinates of the character in the font atlas 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 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 with coordinates that indicate which small portion of the font atlas to display (that portion corresponds to the character). This is all done automatically, thanks to a font atlas stored in the `fontmaps` folder. There needs to be one font atlas per font and per font size. Also, there is a configuration text file with the coordinates and size of every character. The software used to generate font maps is AngelCode Bitmap Font Generator. For now, there is only the Segoe font. """ def position_compound(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: coordinates = [coordinates] coordinates = np.array(coordinates) position = np.repeat(coordinates, self.textsizes, axis=0) return dict(position=position) def text_compound(self, text): """Compound variable for the text string. It changes the text map, the character position, and the text width.""" coordinates = self.coordinates if "\n" in text: text = text.split("\n") if type(text) == list: self.textsizes = [len(t) for t in text] text = "".join(text) if type(coordinates) != list:
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, the cumsum of the length of all texts strictly # before d = np.hstack(([0], np.cumsum(self.textsizes)[:-1])) # compensate the offsets for the length of each text offset -= np.repeat(offset[d], self.textsizes) text_width = 0. else: self.textsizes = len(text) text_map = self.get_map(text) offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) text_width = offset[-1] index = np.zeros(len(text)) self.size = len(text) d = dict(text_map=text_map, offset=offset, text_width=text_width, index=index) d.update(self.position_compound(coordinates)) return d def initialize_font(self, font, fontsize): """Initialize the specified font at a given size.""" self.texture, self.matrix, self.get_map = load_font(font, fontsize) def initialize(self, text, coordinates=(0., 0.), font='segoe', fontsize=24, color=None, letter_spacing=None, interline=0., autocolor=None, background_transparent=True, prevent_constrain=False, depth=None, posoffset=None): """Initialize the text template.""" if prevent_constrain: self.constrain_ratio = False if autocolor is not None: color = get_color(autocolor) if color is None: color = self.default_color self.size = len(text) self.primitive_type = 'POINTS' self.interline = interline text_length = self.size self.initialize_font(font, fontsize) self.coordinates = coordinates point_size = float(self.matrix[:,4].max() * self.texture.shape[1]) # template attributes and varyings self.add_attribute("position", vartype="float", ndim=2, data=np.zeros((self.size, 2))) self.add_attribute("offset", vartype="float", ndim=1) self.add_attribute("index", vartype="float", ndim=1) self.add_attribute("text_map", vartype="float", ndim=4) self.add_varying("flat_text_map", vartype="float", flat=True, ndim=4) if posoffset is None: posoffset = (0., 0.) self.add_uniform('posoffset', vartype='float', ndim=2, data=posoffset) # texture self.add_texture("tex_sampler", size=self.texture.shape[:2], ndim=2, ncomponents=self.texture.shape[2], data=self.texture) # pure heuristic (probably bogus) if letter_spacing is None: letter_spacing = (100 + 17. * fontsize) self.add_uniform("spacing", vartype="float", ndim=2, data=(letter_spacing, interline)) self.add_uniform("point_size", vartype="float", ndim=1, data=point_size) # one color per if isinstance(color, np.ndarray) and color.ndim > 1: self.add_attribute('color0', vartype="float", ndim=4, data=color) self.add_varying('color', vartype="float", ndim=4) self.add_vertex_main('color = color0;') else: self.add_uniform("color", vartype="float", ndim=4, data=color) self.add_uniform("text_width", vartype="float", ndim=1) # compound variables self.add_compound("text", fun=self.text_compound, data=text) self.add_compound("coordinates", fun=self.position_compound, data=coordinates) # vertex shader self.add_vertex_main(VS, after='viewport') # fragment shader self.add_fragment_main(FS(background_transparent)) self.depth = depth
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_Position.xy = gl_Position.xy + posoffset / window_size; gl_PointSize = point_size; flat_text_map = text_map; """ def FS(background_transparent=True): if background_transparent: background_transparent_shader = "letter_alpha" else: background_transparent_shader = "1." fs = """ // relative coordinates of the pixel within the sprite (in [0,1]) float x = gl_PointCoord.x; float y = gl_PointCoord.y; // size of the corresponding character float w = flat_text_map.z; float h = flat_text_map.w; // display the character at the left of the sprite float delta = h / w; x = delta * x; if ((x >= 0) && (x <= 1)) { // coordinates of the character in the font atlas 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):
shader.""" if coordinates is None: coordinates = (0., 0.) if type(coordinates) == tuple: coordinates = [coordinates] coordinates = np.array(coordinates) position = np.repeat(coordinates, self.textsizes, axis=0) return dict(position=position) def text_compound(self, text): """Compound variable for the text string. It changes the text map, the character position, and the text width.""" coordinates = self.coordinates if "\n" in text: text = text.split("\n") if type(text) == list: self.textsizes = [len(t) for t in text] text = "".join(text) if type(coordinates) != list: coordinates = [coordinates] * len(self.textsizes) 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, the cumsum of the length of all texts strictly # before d = np.hstack(([0], np.cumsum(self.textsizes)[:-1])) # compensate the offsets for the length of each text offset -= np.repeat(offset[d], self.textsizes) text_width = 0. else: self.textsizes = len(text) text_map = self.get_map(text) offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) text_width = offset[-1] index = np.zeros(len(text)) self.size = len(text) d = dict(text_map=text_map, offset=offset, text_width=text_width, index=index) d.update(self.position_compound(coordinates)) return d def initialize_font(self, font, fontsize): """Initialize the specified font at a given size.""" self.texture, self.matrix, self.get_map = load_font(font, fontsize) def initialize(self, text, coordinates=(0., 0.), font='segoe', fontsize=24, color=None, letter_spacing=None, interline=0., autocolor=None, background_transparent=True, prevent_constrain=False, depth=None, posoffset=None): """Initialize the text template.""" if prevent_constrain: self.constrain_ratio = False if autocolor is not None: color = get_color(autocolor) if color is None: color = self.default_color self.size = len(text) self.primitive_type = 'POINTS' self.interline = interline text_length = self.size self.initialize_font(font, fontsize) self.coordinates = coordinates point_size = float(self.matrix[:,4].max() * self.texture.shape[1]) # template attributes and varyings self.add_attribute("position", vartype="float", ndim=2, data=np.zeros((self.size, 2))) self.add_attribute("offset", vartype="float", ndim=1) self.add_attribute("index", vartype="float", ndim=1) self.add_attribute("text_map", vartype="float", ndim=4) self.add_varying("flat_text_map", vartype="float", flat=True, ndim=4) if posoffset is None: posoffset = (0., 0.) self.add_uniform('posoffset', vartype='float', ndim=2, data=posoffset) # texture self.add_texture("tex_sampler", size=self.texture.shape[:2], ndim=2, ncomponents=self.texture.shape[2], data=self.texture) # pure heuristic (probably bogus) if letter_spacing is None: letter_spacing = (100 + 17. * fontsize) self.add_uniform("spacing", vartype="float", ndim=2, data=(letter_spacing, interline)) self.add_uniform("point_size", vartype="float", ndim=1, data=point_size) # one color per if isinstance(color, np.ndarray) and color.ndim > 1: self.add_attribute('color0', vartype="float", ndim=4, data=color) self.add_varying('color', vartype="float", ndim=4) self.add_vertex_main('color = color0;') else: self.add_uniform("color", vartype="float", ndim=4, data=color) self.add_uniform("text_width", vartype="float", ndim=1) # compound variables self.add_compound("text", fun=self.text_compound, data=text) self.add_compound("coordinates", fun=self.position_compound, data=coordinates) # vertex shader self.add_vertex_main(VS, after='viewport') # fragment shader self.add_fragment_main(FS(background_transparent)) self.depth = depth
"""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 with coordinates that indicate which small portion of the font atlas to display (that portion corresponds to the character). This is all done automatically, thanks to a font atlas stored in the `fontmaps` folder. There needs to be one font atlas per font and per font size. Also, there is a configuration text file with the coordinates and size of every character. The software used to generate font maps is AngelCode Bitmap Font Generator. For now, there is only the Segoe font. """ def position_compound(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
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_Position.xy = gl_Position.xy + posoffset / window_size; gl_PointSize = point_size; flat_text_map = text_map; """ def FS(background_transparent=True): if background_transparent: background_transparent_shader = "letter_alpha" else: background_transparent_shader = "1." fs = """ // relative coordinates of the pixel within the sprite (in [0,1]) float x = gl_PointCoord.x; float y = gl_PointCoord.y; // size of the corresponding character float w = flat_text_map.z; float h = flat_text_map.w; // display the character at the left of the sprite float delta = h / w; x = delta * x; if ((x >= 0) && (x <= 1)) { // coordinates of the character in the font atlas 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 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 with coordinates that indicate which small portion of the font atlas to display (that portion corresponds to the character). This is all done automatically, thanks to a font atlas stored in the `fontmaps` folder. There needs to be one font atlas per font and per font size. Also, there is a configuration text file with the coordinates and size of every character. The software used to generate font maps is AngelCode Bitmap Font Generator. For now, there is only the Segoe font. """ def
(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: coordinates = [coordinates] coordinates = np.array(coordinates) position = np.repeat(coordinates, self.textsizes, axis=0) return dict(position=position) def text_compound(self, text): """Compound variable for the text string. It changes the text map, the character position, and the text width.""" coordinates = self.coordinates if "\n" in text: text = text.split("\n") if type(text) == list: self.textsizes = [len(t) for t in text] text = "".join(text) if type(coordinates) != list: coordinates = [coordinates] * len(self.textsizes) 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, the cumsum of the length of all texts strictly # before d = np.hstack(([0], np.cumsum(self.textsizes)[:-1])) # compensate the offsets for the length of each text offset -= np.repeat(offset[d], self.textsizes) text_width = 0. else: self.textsizes = len(text) text_map = self.get_map(text) offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) text_width = offset[-1] index = np.zeros(len(text)) self.size = len(text) d = dict(text_map=text_map, offset=offset, text_width=text_width, index=index) d.update(self.position_compound(coordinates)) return d def initialize_font(self, font, fontsize): """Initialize the specified font at a given size.""" self.texture, self.matrix, self.get_map = load_font(font, fontsize) def initialize(self, text, coordinates=(0., 0.), font='segoe', fontsize=24, color=None, letter_spacing=None, interline=0., autocolor=None, background_transparent=True, prevent_constrain=False, depth=None, posoffset=None): """Initialize the text template.""" if prevent_constrain: self.constrain_ratio = False if autocolor is not None: color = get_color(autocolor) if color is None: color = self.default_color self.size = len(text) self.primitive_type = 'POINTS' self.interline = interline text_length = self.size self.initialize_font(font, fontsize) self.coordinates = coordinates point_size = float(self.matrix[:,4].max() * self.texture.shape[1]) # template attributes and varyings self.add_attribute("position", vartype="float", ndim=2, data=np.zeros((self.size, 2))) self.add_attribute("offset", vartype="float", ndim=1) self.add_attribute("index", vartype="float", ndim=1) self.add_attribute("text_map", vartype="float", ndim=4) self.add_varying("flat_text_map", vartype="float", flat=True, ndim=4) if posoffset is None: posoffset = (0., 0.) self.add_uniform('posoffset', vartype='float', ndim=2, data=posoffset) # texture self.add_texture("tex_sampler", size=self.texture.shape[:2], ndim=2, ncomponents=self.texture.shape[2], data=self.texture) # pure heuristic (probably bogus) if letter_spacing is None: letter_spacing = (100 + 17. * fontsize) self.add_uniform("spacing", vartype="float", ndim=2, data=(letter_spacing, interline)) self.add_uniform("point_size", vartype="float", ndim=1, data=point_size) # one color per if isinstance(color, np.ndarray) and color.ndim > 1: self.add_attribute('color0', vartype="float", ndim=4, data=color) self.add_varying('color', vartype="float", ndim=4) self.add_vertex_main('color = color0;') else: self.add_uniform("color", vartype="float", ndim=4, data=color) self.add_uniform("text_width", vartype="float", ndim=1) # compound variables self.add_compound("text", fun=self.text_compound, data=text) self.add_compound("coordinates", fun=self.position_compound, data=coordinates) # vertex shader self.add_vertex_main(VS, after='viewport') # fragment shader self.add_fragment_main(FS(background_transparent)) self.depth = depth
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_Position.xy = gl_Position.xy + posoffset / window_size; gl_PointSize = point_size; flat_text_map = text_map; """ def FS(background_transparent=True): if background_transparent: background_transparent_shader = "letter_alpha" else: background_transparent_shader = "1." fs = """ // relative coordinates of the pixel within the sprite (in [0,1]) float x = gl_PointCoord.x; float y = gl_PointCoord.y; // size of the corresponding character float w = flat_text_map.z; float h = flat_text_map.w; // display the character at the left of the sprite float delta = h / w;
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 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 with coordinates that indicate which small portion of the font atlas to display (that portion corresponds to the character). This is all done automatically, thanks to a font atlas stored in the `fontmaps` folder. There needs to be one font atlas per font and per font size. Also, there is a configuration text file with the coordinates and size of every character. The software used to generate font maps is AngelCode Bitmap Font Generator. For now, there is only the Segoe font. """ def position_compound(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: coordinates = [coordinates] coordinates = np.array(coordinates) position = np.repeat(coordinates, self.textsizes, axis=0) return dict(position=position) def text_compound(self, text): """Compound variable for the text string. It changes the text map, the character position, and the text width.""" coordinates = self.coordinates if "\n" in text: text = text.split("\n") if type(text) == list: self.textsizes = [len(t) for t in text] text = "".join(text) if type(coordinates) != list: coordinates = [coordinates] * len(self.textsizes) 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, the cumsum of the length of all texts strictly # before d = np.hstack(([0], np.cumsum(self.textsizes)[:-1])) # compensate the offsets for the length of each text offset -= np.repeat(offset[d], self.textsizes) text_width = 0. else: self.textsizes = len(text) text_map = self.get_map(text) offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) text_width = offset[-1] index = np.zeros(len(text)) self.size = len(text) d = dict(text_map=text_map, offset=offset, text_width=text_width, index=index) d.update(self.position_compound(coordinates)) return d def initialize_font(self, font, fontsize): """Initialize the specified font at a given size.""" self.texture, self.matrix, self.get_map = load_font(font, fontsize) def initialize(self, text, coordinates=(0., 0.), font='segoe', fontsize=24, color=None, letter_spacing=None, interline=0., autocolor=None, background_transparent=True, prevent_constrain=False, depth=None, posoffset=None): """Initialize the text template.""" if prevent_constrain: self.constrain_ratio = False if autocolor is not None: color = get_color(autocolor) if color is None: color = self.default_color self.size = len(text) self.primitive_type = 'POINTS' self.interline = interline text_length = self.size self.initialize_font(font, fontsize) self.coordinates = coordinates point_size = float(self.matrix[:,4].max() * self.texture.shape[1]) # template attributes and varyings self.add_attribute("position", vartype="float", ndim=2, data=np.zeros((self.size, 2))) self.add_attribute("offset", vartype="float", ndim=1) self.add_attribute("index", vartype="float", ndim=1) self.add_attribute("text_map", vartype="float", ndim=4) self.add_varying("flat_text_map", vartype="float", flat=True, ndim=4) if posoffset is None: posoffset = (0., 0.) self.add_uniform('posoffset', vartype='float', ndim=2, data=posoffset) # texture self.add_texture("tex_sampler", size=self.texture.shape[:2], ndim=2, ncomponents=self.texture.shape[2], data=self.texture) # pure heuristic (probably bogus) if letter_spacing is None: letter_spacing = (100 + 17. * fontsize) self.add_uniform("spacing", vartype="float", ndim=2, data=(letter_spacing, interline)) self.add_uniform("point_size", vartype="float", ndim=1, data=point_size) # one color per if isinstance(color, np.ndarray) and color.ndim > 1: self.add_attribute('color0', vartype="float", ndim=4, data=color) self.add_varying('color', vartype="float", ndim=4) self.add_vertex_main('color = color0;') else: self.add_uniform("color", vartype="float", ndim=4, data=color) self.add_uniform("text_width", vartype="float", ndim=1) # compound variables self.add_compound("text", fun=self.text_compound, data=text) self.add_compound("coordinates", fun=self.position_compound, data=coordinates) # vertex shader self.add_vertex_main(VS, after='viewport') # fragment shader self.add_fragment_main(FS(background_transparent)) self.depth = depth
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: WebGLRenderTarget; readBuffer: WebGLRenderTarget; passes: Pass[]; copyPass: ShaderPass; swapBuffers(): void; addPass(pass: any): void; insertPass(pass: any, index: number): void; render(delta?: number): void; reset(renderTarget?: WebGLRenderTarget): void; setSize(width: number, height: number): void; } export class Pass{ // if set to true, the pass is processed by the composer enabled: boolean;
// 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: WebGLRenderTarget; readBuffer: WebGLRenderTarget; passes: Pass[]; copyPass: ShaderPass; swapBuffers(): void; addPass(pass: any): void; insertPass(pass: any, index: number): void; render(delta?: number): void; reset(renderTarget?: WebGLRenderTarget): void; setSize(width: number, height: number): void; } export class
{ // 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 rendered to screen renderToScreen: boolean; setSize(width: number, height:number ): void; render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number, maskActive?: boolean): void; }
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 # less typing _attrTraits=[ ] def __init__(self,**kw): woo.core.Preprocessor.__init__(self) self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw) def __call__(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=[ _PAT(int,'nSpheres',5,'Total number of spheres'), _PAT(int,'nFall',1,'The number of spheres which are out of the equilibrium position at the beginning.'), _PAT(float,'fallAngle',pi/4.,unit='deg',doc='Initial angle of falling spheres.'), _PAT(float,'rad',.005,unit='m',doc='Radius of spheres'), _PAT(Vector2,'cabHtWd',(.1,.1),unit='m',doc='Height and width of the suspension'), _PAT(float,'cabRad',.0005,unit='m',doc='Radius of the suspending cables'), _PAT(woo.models.ContactModelSelector,'model',woo.models.ContactModelSelector(name='Hertz',restitution=.99,numMat=(1,2),matDesc=['spheres','cables'],mats=[FrictMat(density=3e3,young=2e8),FrictMat(density=.001,young=2e8)]),doc='Select contact model. The first material is for spheres; the second, optional, material, is for the suspension cables.'), _PAT(Vector3,'gravity',(0,0,-9.81),'Gravity acceleration'), _PAT(int,'plotEvery',10,'How often to collect plot data'), _PAT(float,'dtSafety',.7,':obj:`woo.core.Scene.dtSafety`') ] def __init__(self,**kw): woo.core.Preprocessor.__init__(self) self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw) def __call__(self):
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.lab.dynDt.maxRelInc=1e-6 S.trackEnergy=True S.plot.plots={'i':('total','**S.energy')} return S
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] if len(pre.model.mats)>1 else mat) ht=pre.cabHtWd[0] for i,x in enumerate(xx): 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) for p in [Vector3(x,-pre.cabHtWd[1]/2,pre.cabHtWd[0]),Vector3(x,pre.cabHtWd[1]/2,pre.cabHtWd[0])]: t=Truss.make([n,p],radius=pre.cabRad,wire=False,color=color,mat=cabMat,fixed=None) t.shape.nodes[1].blocked='xyzXYZ' S.dem.par.add(t)
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 # less typing _attrTraits=[ ] def __init__(self,**kw): woo.core.Preprocessor.__init__(self) self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw) def
(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=[ _PAT(int,'nSpheres',5,'Total number of spheres'), _PAT(int,'nFall',1,'The number of spheres which are out of the equilibrium position at the beginning.'), _PAT(float,'fallAngle',pi/4.,unit='deg',doc='Initial angle of falling spheres.'), _PAT(float,'rad',.005,unit='m',doc='Radius of spheres'), _PAT(Vector2,'cabHtWd',(.1,.1),unit='m',doc='Height and width of the suspension'), _PAT(float,'cabRad',.0005,unit='m',doc='Radius of the suspending cables'), _PAT(woo.models.ContactModelSelector,'model',woo.models.ContactModelSelector(name='Hertz',restitution=.99,numMat=(1,2),matDesc=['spheres','cables'],mats=[FrictMat(density=3e3,young=2e8),FrictMat(density=.001,young=2e8)]),doc='Select contact model. The first material is for spheres; the second, optional, material, is for the suspension cables.'), _PAT(Vector3,'gravity',(0,0,-9.81),'Gravity acceleration'), _PAT(int,'plotEvery',10,'How often to collect plot data'), _PAT(float,'dtSafety',.7,':obj:`woo.core.Scene.dtSafety`') ] def __init__(self,**kw): 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 called xx=numpy.linspace(0,(pre.nSpheres-1)*2*pre.rad,num=pre.nSpheres) mat=pre.model.mats[0] cabMat=(pre.model.mats[1] if len(pre.model.mats)>1 else mat) ht=pre.cabHtWd[0] for i,x in enumerate(xx): 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) for p in [Vector3(x,-pre.cabHtWd[1]/2,pre.cabHtWd[0]),Vector3(x,pre.cabHtWd[1]/2,pre.cabHtWd[0])]: t=Truss.make([n,p],radius=pre.cabRad,wire=False,color=color,mat=cabMat,fixed=None) t.shape.nodes[1].blocked='xyzXYZ' S.dem.par.add(t) 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.lab.dynDt.maxRelInc=1e-6 S.trackEnergy=True S.plot.plots={'i':('total','**S.energy')} return S
__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 # less typing _attrTraits=[ ] def __init__(self,**kw): woo.core.Preprocessor.__init__(self) self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw) def __call__(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=[ _PAT(int,'nSpheres',5,'Total number of spheres'), _PAT(int,'nFall',1,'The number of spheres which are out of the equilibrium position at the beginning.'), _PAT(float,'fallAngle',pi/4.,unit='deg',doc='Initial angle of falling spheres.'), _PAT(float,'rad',.005,unit='m',doc='Radius of spheres'), _PAT(Vector2,'cabHtWd',(.1,.1),unit='m',doc='Height and width of the suspension'), _PAT(float,'cabRad',.0005,unit='m',doc='Radius of the suspending cables'), _PAT(woo.models.ContactModelSelector,'model',woo.models.ContactModelSelector(name='Hertz',restitution=.99,numMat=(1,2),matDesc=['spheres','cables'],mats=[FrictMat(density=3e3,young=2e8),FrictMat(density=.001,young=2e8)]),doc='Select contact model. The first material is for spheres; the second, optional, material, is for the suspension cables.'), _PAT(Vector3,'gravity',(0,0,-9.81),'Gravity acceleration'), _PAT(int,'plotEvery',10,'How often to collect plot data'), _PAT(float,'dtSafety',.7,':obj:`woo.core.Scene.dtSafety`') ] def __init__(self,**kw): 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 called xx=numpy.linspace(0,(pre.nSpheres-1)*2*pre.rad,num=pre.nSpheres) mat=pre.model.mats[0] cabMat=(pre.model.mats[1] if len(pre.model.mats)>1 else mat) ht=pre.cabHtWd[0] for i,x in enumerate(xx):
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.lab.dynDt.maxRelInc=1e-6 S.trackEnergy=True S.plot.plots={'i':('total','**S.energy')} return S
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) for p in [Vector3(x,-pre.cabHtWd[1]/2,pre.cabHtWd[0]),Vector3(x,pre.cabHtWd[1]/2,pre.cabHtWd[0])]: t=Truss.make([n,p],radius=pre.cabRad,wire=False,color=color,mat=cabMat,fixed=None) t.shape.nodes[1].blocked='xyzXYZ' S.dem.par.add(t)
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 # less typing _attrTraits=[ ] def __init__(self,**kw): woo.core.Preprocessor.__init__(self) self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw) def __call__(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=[ _PAT(int,'nSpheres',5,'Total number of spheres'), _PAT(int,'nFall',1,'The number of spheres which are out of the equilibrium position at the beginning.'), _PAT(float,'fallAngle',pi/4.,unit='deg',doc='Initial angle of falling spheres.'), _PAT(float,'rad',.005,unit='m',doc='Radius of spheres'), _PAT(Vector2,'cabHtWd',(.1,.1),unit='m',doc='Height and width of the suspension'), _PAT(float,'cabRad',.0005,unit='m',doc='Radius of the suspending cables'), _PAT(woo.models.ContactModelSelector,'model',woo.models.ContactModelSelector(name='Hertz',restitution=.99,numMat=(1,2),matDesc=['spheres','cables'],mats=[FrictMat(density=3e3,young=2e8),FrictMat(density=.001,young=2e8)]),doc='Select contact model. The first material is for spheres; the second, optional, material, is for the suspension cables.'), _PAT(Vector3,'gravity',(0,0,-9.81),'Gravity acceleration'),
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 called xx=numpy.linspace(0,(pre.nSpheres-1)*2*pre.rad,num=pre.nSpheres) mat=pre.model.mats[0] cabMat=(pre.model.mats[1] if len(pre.model.mats)>1 else mat) ht=pre.cabHtWd[0] for i,x in enumerate(xx): 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) for p in [Vector3(x,-pre.cabHtWd[1]/2,pre.cabHtWd[0]),Vector3(x,pre.cabHtWd[1]/2,pre.cabHtWd[0])]: t=Truss.make([n,p],radius=pre.cabRad,wire=False,color=color,mat=cabMat,fixed=None) t.shape.nodes[1].blocked='xyzXYZ' S.dem.par.add(t) 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.lab.dynDt.maxRelInc=1e-6 S.trackEnergy=True S.plot.plots={'i':('total','**S.energy')} return S
_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 <[email protected]> # # 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 RIOT periph_uart test. """ try: from riot_pal import DutShell
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(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.""" return self.send_cmd("send {} {}".format(dev, test_string))
except ImportError:
random_line_split
periph_uart_if.py
# Copyright (c) 2018 Kevin Weiss, for HAW Hamburg <[email protected]> # # 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 RIOT periph_uart test. """ try: from riot_pal import DutShell except ImportError: 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):
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.""" return self.send_cmd("send {} {}".format(dev, test_string))
"""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 <[email protected]> # # 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 RIOT periph_uart test. """ try: from riot_pal import DutShell except ImportError: 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(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
(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 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. import { Component, OnInit, ViewChild, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef, ElementRef, OnDestroy } from '@angular/core'; import { TagService } from '../service/tag.service'; import { ErrorHandler } from '../error-handler/error-handler'; import { ConfirmationTargets, ConfirmationState, ConfirmationButtons } from '../shared/shared.const'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message'; import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message'; import { Tag, TagClickEvent } from '../service/interface'; import { TAG_TEMPLATE } from './tag.component.html'; import { TAG_STYLE } from './tag.component.css'; import { toPromise, CustomComparator, VULNERABILITY_SCAN_STATUS } from '../utils'; import { TranslateService } from '@ngx-translate/core'; import { State, Comparator } from 'clarity-angular'; import { ScanningResultService } from '../service/index'; import { Observable, Subscription } from 'rxjs/Rx'; const STATE_CHECK_INTERVAL: number = 2000;//2s @Component({ selector: 'hbr-tag', template: TAG_TEMPLATE, styles: [TAG_STYLE], changeDetection: ChangeDetectionStrategy.OnPush }) export class TagComponent 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 = new EventEmitter<boolean>(); @Output() tagClickEvent = new EventEmitter<TagClickEvent>(); tags: Tag[]; showTagManifestOpened: boolean; manifestInfoTitle: string; digestId: string; staticBackdrop: boolean = true; closable: boolean = false; createdComparator: Comparator<Tag> = new CustomComparator<Tag>('created', 'date'); loading: boolean = false; stateCheckTimer: Subscription; tagsInScanning: { [key: string]: any } = {}; scanningTagCount: number = 0; copyFailed: boolean = false; @ViewChild('confirmationDialog') confirmationDialog: ConfirmationDialogComponent; @ViewChild('digestTarget') textInput: ElementRef; constructor( private errorHandler: ErrorHandler, private tagService: TagService, private translateService: TranslateService, private scanningService: ScanningResultService, private ref: ChangeDetectorRef) { } confirmDeletion(message: ConfirmationAcknowledgement) { if (message && message.source === ConfirmationTargets.TAG && message.state === ConfirmationState.CONFIRMED) { let tag: Tag = message.data; if (tag) { if (tag.signature) { return; } else { toPromise<number>(this.tagService .deleteTag(this.repoName, tag.name)) .then( response => { this.retrieve(); this.translateService.get('REPOSITORY.DELETED_TAG_SUCCESS') .subscribe(res => this.errorHandler.info(res)); }).catch(error => this.errorHandler.error(error)); } } } } ngOnInit() { if (!this.projectId) { this.errorHandler.error('Project ID cannot be unset.'); return; } if (!this.repoName) { this.errorHandler.error('Repo name cannot be unset.'); return; } this.retrieve(); this.stateCheckTimer = Observable.timer(STATE_CHECK_INTERVAL, STATE_CHECK_INTERVAL).subscribe(() => { if (this.scanningTagCount > 0) { this.updateScanningStates(); } }); } ngOnDestroy(): void { if (this.stateCheckTimer) { this.stateCheckTimer.unsubscribe(); } } 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); } }) .catch(error => { this.errorHandler.error(error); this.loading = false; }); let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 1000); } deleteTag(tag: Tag) { if (tag) { let titleKey: string, summaryKey: string, content: string, buttons: ConfirmationButtons; if (tag.signature) { titleKey = 'REPOSITORY.DELETION_TITLE_TAG_DENIED'; summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG_DENIED'; buttons = ConfirmationButtons.CLOSE; content = 'notary -s https://' + this.registryUrl + ':4443 -d ~/.docker/trust remove -p ' + this.registryUrl + '/' + this.repoName + ' ' + tag.name; } else { titleKey = 'REPOSITORY.DELETION_TITLE_TAG'; summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG'; buttons = ConfirmationButtons.DELETE_CANCEL; content = tag.name; } let message = new ConfirmationMessage( titleKey, summaryKey, content, tag, ConfirmationTargets.TAG, buttons); this.confirmationDialog.open(message); } } showDigestId(tag: Tag) { if (tag) { this.manifestInfoTitle = 'REPOSITORY.COPY_DIGEST_ID'; this.digestId = tag.digest; this.showTagManifestOpened = true; this.copyFailed = false; } } onTagClick(tag: Tag): void { if (tag) { let evt: TagClickEvent = { project_id: this.projectId, repository_name: this.repoName, tag_name: tag.name }; this.tagClickEvent.emit(evt); } } scanTag(tagId: string): void { //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; }) .catch(error => this.errorHandler.error(error)); } 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 => { if (item.scan_overview) { if (item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.pending || item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.running) { this.tagsInScanning[item.name] = item.name; this.scanningTagCount += 1; } } }); this.tags = items; }) .catch(error => { this.errorHandler.error(error); }); let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 1000); } onSuccess($event: any): void { this.copyFailed = false; //Directly close dialog this.showTagManifestOpened = false; } onError($event: any): void { //Show error this.copyFailed = true; //Select all text if(this.textInput){ this.textInput.nativeElement.select(); } } }
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 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. import { Component, OnInit, ViewChild, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef, ElementRef, OnDestroy } from '@angular/core'; import { TagService } from '../service/tag.service'; import { ErrorHandler } from '../error-handler/error-handler'; import { ConfirmationTargets, ConfirmationState, ConfirmationButtons } from '../shared/shared.const'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message'; import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message'; import { Tag, TagClickEvent } from '../service/interface'; import { TAG_TEMPLATE } from './tag.component.html'; import { TAG_STYLE } from './tag.component.css'; import { toPromise, CustomComparator, VULNERABILITY_SCAN_STATUS } from '../utils'; import { TranslateService } from '@ngx-translate/core'; import { State, Comparator } from 'clarity-angular'; import { ScanningResultService } from '../service/index'; import { Observable, Subscription } from 'rxjs/Rx'; const STATE_CHECK_INTERVAL: number = 2000;//2s @Component({ selector: 'hbr-tag', template: TAG_TEMPLATE, styles: [TAG_STYLE], changeDetection: ChangeDetectionStrategy.OnPush }) export class
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 = new EventEmitter<boolean>(); @Output() tagClickEvent = new EventEmitter<TagClickEvent>(); tags: Tag[]; showTagManifestOpened: boolean; manifestInfoTitle: string; digestId: string; staticBackdrop: boolean = true; closable: boolean = false; createdComparator: Comparator<Tag> = new CustomComparator<Tag>('created', 'date'); loading: boolean = false; stateCheckTimer: Subscription; tagsInScanning: { [key: string]: any } = {}; scanningTagCount: number = 0; copyFailed: boolean = false; @ViewChild('confirmationDialog') confirmationDialog: ConfirmationDialogComponent; @ViewChild('digestTarget') textInput: ElementRef; constructor( private errorHandler: ErrorHandler, private tagService: TagService, private translateService: TranslateService, private scanningService: ScanningResultService, private ref: ChangeDetectorRef) { } confirmDeletion(message: ConfirmationAcknowledgement) { if (message && message.source === ConfirmationTargets.TAG && message.state === ConfirmationState.CONFIRMED) { let tag: Tag = message.data; if (tag) { if (tag.signature) { return; } else { toPromise<number>(this.tagService .deleteTag(this.repoName, tag.name)) .then( response => { this.retrieve(); this.translateService.get('REPOSITORY.DELETED_TAG_SUCCESS') .subscribe(res => this.errorHandler.info(res)); }).catch(error => this.errorHandler.error(error)); } } } } ngOnInit() { if (!this.projectId) { this.errorHandler.error('Project ID cannot be unset.'); return; } if (!this.repoName) { this.errorHandler.error('Repo name cannot be unset.'); return; } this.retrieve(); this.stateCheckTimer = Observable.timer(STATE_CHECK_INTERVAL, STATE_CHECK_INTERVAL).subscribe(() => { if (this.scanningTagCount > 0) { this.updateScanningStates(); } }); } ngOnDestroy(): void { if (this.stateCheckTimer) { this.stateCheckTimer.unsubscribe(); } } 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); } }) .catch(error => { this.errorHandler.error(error); this.loading = false; }); let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 1000); } deleteTag(tag: Tag) { if (tag) { let titleKey: string, summaryKey: string, content: string, buttons: ConfirmationButtons; if (tag.signature) { titleKey = 'REPOSITORY.DELETION_TITLE_TAG_DENIED'; summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG_DENIED'; buttons = ConfirmationButtons.CLOSE; content = 'notary -s https://' + this.registryUrl + ':4443 -d ~/.docker/trust remove -p ' + this.registryUrl + '/' + this.repoName + ' ' + tag.name; } else { titleKey = 'REPOSITORY.DELETION_TITLE_TAG'; summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG'; buttons = ConfirmationButtons.DELETE_CANCEL; content = tag.name; } let message = new ConfirmationMessage( titleKey, summaryKey, content, tag, ConfirmationTargets.TAG, buttons); this.confirmationDialog.open(message); } } showDigestId(tag: Tag) { if (tag) { this.manifestInfoTitle = 'REPOSITORY.COPY_DIGEST_ID'; this.digestId = tag.digest; this.showTagManifestOpened = true; this.copyFailed = false; } } onTagClick(tag: Tag): void { if (tag) { let evt: TagClickEvent = { project_id: this.projectId, repository_name: this.repoName, tag_name: tag.name }; this.tagClickEvent.emit(evt); } } scanTag(tagId: string): void { //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; }) .catch(error => this.errorHandler.error(error)); } 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 => { if (item.scan_overview) { if (item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.pending || item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.running) { this.tagsInScanning[item.name] = item.name; this.scanningTagCount += 1; } } }); this.tags = items; }) .catch(error => { this.errorHandler.error(error); }); let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 1000); } onSuccess($event: any): void { this.copyFailed = false; //Directly close dialog this.showTagManifestOpened = false; } onError($event: any): void { //Show error this.copyFailed = true; //Select all text if(this.textInput){ this.textInput.nativeElement.select(); } } }
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 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. import { Component, OnInit, ViewChild, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef, ElementRef, OnDestroy } from '@angular/core'; import { TagService } from '../service/tag.service'; import { ErrorHandler } from '../error-handler/error-handler'; import { ConfirmationTargets, ConfirmationState, ConfirmationButtons } from '../shared/shared.const'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message'; import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message'; import { Tag, TagClickEvent } from '../service/interface'; import { TAG_TEMPLATE } from './tag.component.html'; import { TAG_STYLE } from './tag.component.css'; import { toPromise, CustomComparator, VULNERABILITY_SCAN_STATUS } from '../utils'; import { TranslateService } from '@ngx-translate/core'; import { State, Comparator } from 'clarity-angular'; import { ScanningResultService } from '../service/index'; import { Observable, Subscription } from 'rxjs/Rx'; const STATE_CHECK_INTERVAL: number = 2000;//2s @Component({ selector: 'hbr-tag', template: TAG_TEMPLATE, styles: [TAG_STYLE], changeDetection: ChangeDetectionStrategy.OnPush }) export class TagComponent 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 = new EventEmitter<boolean>(); @Output() tagClickEvent = new EventEmitter<TagClickEvent>(); tags: Tag[]; showTagManifestOpened: boolean; manifestInfoTitle: string; digestId: string; staticBackdrop: boolean = true; closable: boolean = false; createdComparator: Comparator<Tag> = new CustomComparator<Tag>('created', 'date'); loading: boolean = false; stateCheckTimer: Subscription; tagsInScanning: { [key: string]: any } = {}; scanningTagCount: number = 0; copyFailed: boolean = false; @ViewChild('confirmationDialog') confirmationDialog: ConfirmationDialogComponent; @ViewChild('digestTarget') textInput: ElementRef; constructor( private errorHandler: ErrorHandler, private tagService: TagService, private translateService: TranslateService, private scanningService: ScanningResultService, private ref: ChangeDetectorRef) { } confirmDeletion(message: ConfirmationAcknowledgement) { if (message && message.source === ConfirmationTargets.TAG && message.state === ConfirmationState.CONFIRMED) { let tag: Tag = message.data; if (tag) { if (tag.signature) { return; } else { toPromise<number>(this.tagService .deleteTag(this.repoName, tag.name)) .then( response => { this.retrieve(); this.translateService.get('REPOSITORY.DELETED_TAG_SUCCESS') .subscribe(res => this.errorHandler.info(res)); }).catch(error => this.errorHandler.error(error)); } } } } ngOnInit() { if (!this.projectId) { this.errorHandler.error('Project ID cannot be unset.'); return; } if (!this.repoName) { this.errorHandler.error('Repo name cannot be unset.'); return; } this.retrieve(); this.stateCheckTimer = Observable.timer(STATE_CHECK_INTERVAL, STATE_CHECK_INTERVAL).subscribe(() => { if (this.scanningTagCount > 0) { this.updateScanningStates(); } }); } ngOnDestroy(): void { if (this.stateCheckTimer) { this.stateCheckTimer.unsubscribe(); } } 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); } }) .catch(error => { this.errorHandler.error(error); this.loading = false; }); let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 1000); } deleteTag(tag: Tag) { if (tag) { let titleKey: string, summaryKey: string, content: string, buttons: ConfirmationButtons; if (tag.signature) { titleKey = 'REPOSITORY.DELETION_TITLE_TAG_DENIED'; summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG_DENIED'; buttons = ConfirmationButtons.CLOSE; content = 'notary -s https://' + this.registryUrl + ':4443 -d ~/.docker/trust remove -p ' + this.registryUrl + '/' + this.repoName + ' ' + tag.name; } else { titleKey = 'REPOSITORY.DELETION_TITLE_TAG'; summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG'; buttons = ConfirmationButtons.DELETE_CANCEL; content = tag.name; } let message = new ConfirmationMessage( titleKey, summaryKey, content, tag, ConfirmationTargets.TAG, buttons); this.confirmationDialog.open(message); } } showDigestId(tag: Tag) { if (tag) { this.manifestInfoTitle = 'REPOSITORY.COPY_DIGEST_ID'; this.digestId = tag.digest; this.showTagManifestOpened = true; this.copyFailed = false; } } onTagClick(tag: Tag): void { if (tag) { let evt: TagClickEvent = { project_id: this.projectId, repository_name: this.repoName, tag_name: tag.name }; this.tagClickEvent.emit(evt); } } scanTag(tagId: string): void
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 => { if (item.scan_overview) { if (item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.pending || item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.running) { this.tagsInScanning[item.name] = item.name; this.scanningTagCount += 1; } } }); this.tags = items; }) .catch(error => { this.errorHandler.error(error); }); let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 1000); } onSuccess($event: any): void { this.copyFailed = false; //Directly close dialog this.showTagManifestOpened = false; } onError($event: any): void { //Show error this.copyFailed = true; //Select all text if(this.textInput){ this.textInput.nativeElement.select(); } } }
{ //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; }) .catch(error => this.errorHandler.error(error)); }
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 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. import { Component, OnInit, ViewChild, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef, ElementRef, OnDestroy } from '@angular/core'; import { TagService } from '../service/tag.service'; import { ErrorHandler } from '../error-handler/error-handler'; import { ConfirmationTargets, ConfirmationState, ConfirmationButtons } from '../shared/shared.const'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message'; import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message'; import { Tag, TagClickEvent } from '../service/interface'; import { TAG_TEMPLATE } from './tag.component.html'; import { TAG_STYLE } from './tag.component.css'; import { toPromise, CustomComparator, VULNERABILITY_SCAN_STATUS } from '../utils'; import { TranslateService } from '@ngx-translate/core'; import { State, Comparator } from 'clarity-angular'; import { ScanningResultService } from '../service/index'; import { Observable, Subscription } from 'rxjs/Rx'; const STATE_CHECK_INTERVAL: number = 2000;//2s @Component({ selector: 'hbr-tag', template: TAG_TEMPLATE, styles: [TAG_STYLE], changeDetection: ChangeDetectionStrategy.OnPush }) export class TagComponent 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 = new EventEmitter<boolean>(); @Output() tagClickEvent = new EventEmitter<TagClickEvent>(); tags: Tag[]; showTagManifestOpened: boolean; manifestInfoTitle: string; digestId: string; staticBackdrop: boolean = true; closable: boolean = false; createdComparator: Comparator<Tag> = new CustomComparator<Tag>('created', 'date'); loading: boolean = false; stateCheckTimer: Subscription; tagsInScanning: { [key: string]: any } = {}; scanningTagCount: number = 0; copyFailed: boolean = false; @ViewChild('confirmationDialog') confirmationDialog: ConfirmationDialogComponent; @ViewChild('digestTarget') textInput: ElementRef; constructor( private errorHandler: ErrorHandler, private tagService: TagService, private translateService: TranslateService, private scanningService: ScanningResultService, private ref: ChangeDetectorRef) { } confirmDeletion(message: ConfirmationAcknowledgement) { if (message && message.source === ConfirmationTargets.TAG && message.state === ConfirmationState.CONFIRMED) { let tag: Tag = message.data; if (tag) { if (tag.signature) { return; } else { toPromise<number>(this.tagService .deleteTag(this.repoName, tag.name)) .then( response => { this.retrieve(); this.translateService.get('REPOSITORY.DELETED_TAG_SUCCESS') .subscribe(res => this.errorHandler.info(res)); }).catch(error => this.errorHandler.error(error)); } } } } ngOnInit() { if (!this.projectId) { this.errorHandler.error('Project ID cannot be unset.'); return; } if (!this.repoName) { this.errorHandler.error('Repo name cannot be unset.'); return; } this.retrieve(); this.stateCheckTimer = Observable.timer(STATE_CHECK_INTERVAL, STATE_CHECK_INTERVAL).subscribe(() => { if (this.scanningTagCount > 0) { this.updateScanningStates(); } }); } ngOnDestroy(): void { if (this.stateCheckTimer)
} 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); } }) .catch(error => { this.errorHandler.error(error); this.loading = false; }); let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 1000); } deleteTag(tag: Tag) { if (tag) { let titleKey: string, summaryKey: string, content: string, buttons: ConfirmationButtons; if (tag.signature) { titleKey = 'REPOSITORY.DELETION_TITLE_TAG_DENIED'; summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG_DENIED'; buttons = ConfirmationButtons.CLOSE; content = 'notary -s https://' + this.registryUrl + ':4443 -d ~/.docker/trust remove -p ' + this.registryUrl + '/' + this.repoName + ' ' + tag.name; } else { titleKey = 'REPOSITORY.DELETION_TITLE_TAG'; summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG'; buttons = ConfirmationButtons.DELETE_CANCEL; content = tag.name; } let message = new ConfirmationMessage( titleKey, summaryKey, content, tag, ConfirmationTargets.TAG, buttons); this.confirmationDialog.open(message); } } showDigestId(tag: Tag) { if (tag) { this.manifestInfoTitle = 'REPOSITORY.COPY_DIGEST_ID'; this.digestId = tag.digest; this.showTagManifestOpened = true; this.copyFailed = false; } } onTagClick(tag: Tag): void { if (tag) { let evt: TagClickEvent = { project_id: this.projectId, repository_name: this.repoName, tag_name: tag.name }; this.tagClickEvent.emit(evt); } } scanTag(tagId: string): void { //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; }) .catch(error => this.errorHandler.error(error)); } 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 => { if (item.scan_overview) { if (item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.pending || item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.running) { this.tagsInScanning[item.name] = item.name; this.scanningTagCount += 1; } } }); this.tags = items; }) .catch(error => { this.errorHandler.error(error); }); let hnd = setInterval(() => this.ref.markForCheck(), 100); setTimeout(() => clearInterval(hnd), 1000); } onSuccess($event: any): void { this.copyFailed = false; //Directly close dialog this.showTagManifestOpened = false; } onError($event: any): void { //Show error this.copyFailed = true; //Select all text if(this.textInput){ this.textInput.nativeElement.select(); } } }
{ 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 PanTilt, WS2812, PWM, RGB, GRB, RGBW, GRBW __version__ = '0.0.3' pantilthat = PanTilt(i2c_bus=SMBus(1)) brightness = pantilthat.brightness idle_timeout = pantilthat.idle_timeout clear = pantilthat.clear light_mode = pantilthat.light_mode light_type = pantilthat.light_type servo_one = pantilthat.servo_one servo_pulse_max = pantilthat.servo_pulse_max servo_pulse_min = pantilthat.servo_pulse_min servo_two = pantilthat.servo_two servo_enable = pantilthat.servo_enable set_all = pantilthat.set_all set_pixel = pantilthat.set_pixel set_pixel_rgbw = pantilthat.set_pixel_rgbw show = pantilthat.show pan = pantilthat.servo_one tilt = pantilthat.servo_two
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 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 PanTilt, WS2812, PWM, RGB, GRB, RGBW, GRBW __version__ = '0.0.3' pantilthat = PanTilt(i2c_bus=SMBus(1)) brightness = pantilthat.brightness idle_timeout = pantilthat.idle_timeout clear = pantilthat.clear light_mode = pantilthat.light_mode light_type = pantilthat.light_type servo_one = pantilthat.servo_one servo_pulse_max = pantilthat.servo_pulse_max servo_pulse_min = pantilthat.servo_pulse_min servo_two = pantilthat.servo_two servo_enable = pantilthat.servo_enable set_all = pantilthat.set_all set_pixel = pantilthat.set_pixel
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; beforeEach(async () => await browser.get('/mdc-card')); beforeEach(() => { loader = ProtractorHarnessEnvironment.loader(); }); it('should get card text', async () => { const card = await loader.getHarness(MatCardHarness);
' 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.getTitleText()).toBe('Shiba Inu'); }); it('should get subtitle text', async () => { const card = await loader.getHarness(MatCardHarness); expect(await card.getSubtitleText()).toBe('Dog Breed'); }); });
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
window, such as a palette or toolbox. Utility, /// The window is a splash screen displayed as an application is starting up. Splash, /// This is a dialog window. Dialog, /// A dropdown menu that usually appears when the user clicks on an item in a menu bar. /// This property is typically used on override-redirect windows. DropdownMenu, /// A popup menu that usually appears when the user right clicks on an object. /// This property is typically used on override-redirect windows. PopupMenu, /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor. /// This property is typically used on override-redirect windows. Tooltip, /// The window is a notification. /// This property is typically used on override-redirect windows. Notification, /// This should be used on the windows that are popped up by combo boxes. /// This property is typically used on override-redirect windows. Combo, /// This indicates the the window is being dragged. /// This property is typically used on override-redirect windows. Dnd, /// This is a normal, top-level window. Normal, } impl Default for WindowType { fn default() -> Self { WindowType::Normal } } impl WindowType { pub(crate) fn as_atom(&self, xconn: &Arc<XConnection>) -> ffi::Atom { use self::WindowType::*; let atom_name: &[u8] = match *self { Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0", Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0", Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0", Menu => b"_NET_WM_WINDOW_TYPE_MENU\0", Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0", Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0", Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0", DropdownMenu => b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0", PopupMenu => b"_NET_WM_WINDOW_TYPE_POPUP_MENU\0", Tooltip => b"_NET_WM_WINDOW_TYPE_TOOLTIP\0", Notification => b"_NET_WM_WINDOW_TYPE_NOTIFICATION\0", Combo => b"_NET_WM_WINDOW_TYPE_COMBO\0", Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0", }; 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_ulong; // Motif WM hints are obsolete, but still widely supported. // https://stackoverflow.com/a/1909708 pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0; pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1; pub const MWM_FUNC_ALL: c_ulong = 1 << 0; pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1; pub const MWM_FUNC_MOVE: c_ulong = 1 << 2; pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3; pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4; pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5; } impl MotifHints { pub fn new() -> MotifHints { MotifHints { hints: MwmHints { flags: 0, functions: 0, decorations: 0, input_mode: 0, status: 0, }, } } pub fn set_decorations(&mut self, decorations: bool) { self.hints.flags |= mwm::MWM_HINTS_DECORATIONS; self.hints.decorations = decorations as c_ulong; } pub fn set_maximizable(&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 self.hints.functions & mwm::MWM_FUNC_ALL != 0 { self.hints.functions &= !func; } else { self.hints.functions |= func; } } } fn remove_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 { self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS; self.hints.functions = mwm::MWM_FUNC_ALL; } if self.hints.functions & mwm::MWM_FUNC_ALL != 0 { self.hints.functions |= func; } else { self.hints.functions &= !func; } } } impl MwmHints { fn as_slice(&self) -> &[c_ulong] { unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) } } } pub struct NormalHints<'a> { size_hints: XSmartPointer<'a, ffi::XSizeHints>, } impl<'a> NormalHints<'a> { pub fn new(xconn: &'a XConnection) -> Self { NormalHints { size_hints: xconn.alloc_size_hints(), } } pub fn get_position(&self) -> Option<(i32, i32)> { if has_flag(self.size_hints.flags, ffi::PPosition) { Some((self.size_hints.x as i32, self.size_hints.y as i32)) } else { None } } pub fn set_position(&mut self, position: Option<(i32, i32)>) { if let Some((x, y)) = position { self.size_hints.flags |= ffi::PPosition; self.size_hints.x = x as c_int; self.size_hints.y = y as c_int; } else { self.size_hints.flags &= !ffi::PPosition; } } // WARNING: This hint is obsolete pub fn set_size(&mut self, size: Option<(u32, u32)>) { if let Some((width, height)) = size { self.size_hints.flags |= ffi::PSize; self.size_hints.width = width as c_int; self.size_hints.height = height as c_int; } else { self.size_hints.flags &= !ffi::PSize; } } pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) { if let Some((max_width, max_height)) = max_size { self.size_hints.flags |= ffi::PMaxSize; self.size_hints.max_width = max_width as c_int; self.size_hints.max_height = max_height as c_int; } else { self.size_hints.flags &= !ffi::PMaxSize; } } pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) { if let Some((min_width, min_height)) = min_size { self.size_hints.flags |= ffi::PMinSize; self.size_hints.min_width = min_width as c_int; self.size_hints.min_height = min_height as c_int; } else { self.size_hints.flags &= !ffi::PMinSize; } } pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) { if let Some((width_inc, height_inc)) = resize_increments { self.size_hints.flags |= ffi::PResizeInc; self.size_hints.width_inc = width_inc as c_int; self.size_hints.height_inc = height_inc as c_int; } else { self.size_hints.flags &= !ffi::PResizeInc; } } pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) { if let Some((base_width, base_height)) = base_size { 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; } 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) }; 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
of all other windows. Dock, /// Toolbar windows. "Torn off" from the main application. Toolbar, /// Pinnable menu windows. "Torn off" from the main application. Menu, /// A small persistent utility window, such as a palette or toolbox. Utility, /// The window is a splash screen displayed as an application is starting up. Splash, /// This is a dialog window. Dialog, /// A dropdown menu that usually appears when the user clicks on an item in a menu bar. /// This property is typically used on override-redirect windows. DropdownMenu, /// A popup menu that usually appears when the user right clicks on an object. /// This property is typically used on override-redirect windows. PopupMenu, /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor. /// This property is typically used on override-redirect windows. Tooltip, /// The window is a notification. /// This property is typically used on override-redirect windows. Notification, /// This should be used on the windows that are popped up by combo boxes. /// This property is typically used on override-redirect windows. Combo, /// This indicates the the window is being dragged. /// This property is typically used on override-redirect windows. Dnd, /// This is a normal, top-level window. Normal, } impl Default for WindowType { fn default() -> Self { WindowType::Normal } } impl WindowType { pub(crate) fn as_atom(&self, xconn: &Arc<XConnection>) -> ffi::Atom { use self::WindowType::*; let atom_name: &[u8] = match *self { Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0", Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0", Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0", Menu => b"_NET_WM_WINDOW_TYPE_MENU\0", Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0", Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0", Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0", DropdownMenu => b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0", PopupMenu => b"_NET_WM_WINDOW_TYPE_POPUP_MENU\0", Tooltip => b"_NET_WM_WINDOW_TYPE_TOOLTIP\0", Notification => b"_NET_WM_WINDOW_TYPE_NOTIFICATION\0", Combo => b"_NET_WM_WINDOW_TYPE_COMBO\0",
}; 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_ulong; // Motif WM hints are obsolete, but still widely supported. // https://stackoverflow.com/a/1909708 pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0; pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1; pub const MWM_FUNC_ALL: c_ulong = 1 << 0; pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1; pub const MWM_FUNC_MOVE: c_ulong = 1 << 2; pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3; pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4; pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5; } impl MotifHints { pub fn new() -> MotifHints { MotifHints { hints: MwmHints { flags: 0, functions: 0, decorations: 0, input_mode: 0, status: 0, }, } } pub fn set_decorations(&mut self, decorations: bool) { self.hints.flags |= mwm::MWM_HINTS_DECORATIONS; self.hints.decorations = decorations as c_ulong; } pub fn set_maximizable(&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 self.hints.functions & mwm::MWM_FUNC_ALL != 0 { self.hints.functions &= !func; } else { self.hints.functions |= func; } } } fn remove_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 { self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS; self.hints.functions = mwm::MWM_FUNC_ALL; } if self.hints.functions & mwm::MWM_FUNC_ALL != 0 { self.hints.functions |= func; } else { self.hints.functions &= !func; } } } impl MwmHints { fn as_slice(&self) -> &[c_ulong] { unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) } } } pub struct NormalHints<'a> { size_hints: XSmartPointer<'a, ffi::XSizeHints>, } impl<'a> NormalHints<'a> { pub fn new(xconn: &'a XConnection) -> Self { NormalHints { size_hints: xconn.alloc_size_hints(), } } pub fn get_position(&self) -> Option<(i32, i32)> { if has_flag(self.size_hints.flags, ffi::PPosition) { Some((self.size_hints.x as i32, self.size_hints.y as i32)) } else { None } } pub fn set_position(&mut self, position: Option<(i32, i32)>) { if let Some((x, y)) = position { self.size_hints.flags |= ffi::PPosition; self.size_hints.x = x as c_int; self.size_hints.y = y as c_int; } else { self.size_hints.flags &= !ffi::PPosition; } } // WARNING: This hint is obsolete pub fn set_size(&mut self, size: Option<(u32, u32)>) { if let Some((width, height)) = size { self.size_hints.flags |= ffi::PSize; self.size_hints.width = width as c_int; self.size_hints.height = height as c_int; } else { self.size_hints.flags &= !ffi::PSize; } } pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) { if let Some((max_width, max_height)) = max_size { self.size_hints.flags |= ffi::PMaxSize; self.size_hints.max_width = max_width as c_int; self.size_hints.max_height = max_height as c_int; } else { self.size_hints.flags &= !ffi::PMaxSize; } } pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) { if let Some((min_width, min_height)) = min_size { self.size_hints.flags |= ffi::PMinSize; self.size_hints.min_width = min_width as c_int; self.size_hints.min_height = min_height as c_int; } else { self.size_hints.flags &= !ffi::PMinSize; } } pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) { if let Some((width_inc, height_inc)) = resize_increments { self.size_hints.flags |= ffi::PResizeInc; self.size_hints.width_inc = width_inc as c_int; self.size_hints.height_inc = height_inc as c_int; } else { self.size_hints.flags &= !ffi::PResizeInc; } } pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) { if let Some((base_width, base_height)) = base_size { 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; } 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) }; self.check
Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0",
random_line_split
hint.rs
of all other windows. Dock, /// Toolbar windows. "Torn off" from the main application. Toolbar, /// Pinnable menu windows. "Torn off" from the main application. Menu, /// A small persistent utility window, such as a palette or toolbox. Utility, /// The window is a splash screen displayed as an application is starting up. Splash, /// This is a dialog window. Dialog, /// A dropdown menu that usually appears when the user clicks on an item in a menu bar. /// This property is typically used on override-redirect windows. DropdownMenu, /// A popup menu that usually appears when the user right clicks on an object. /// This property is typically used on override-redirect windows. PopupMenu, /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor. /// This property is typically used on override-redirect windows. Tooltip, /// The window is a notification. /// This property is typically used on override-redirect windows. Notification, /// This should be used on the windows that are popped up by combo boxes. /// This property is typically used on override-redirect windows. Combo, /// This indicates the the window is being dragged. /// This property is typically used on override-redirect windows. Dnd, /// This is a normal, top-level window. Normal, } impl Default for WindowType { fn default() -> Self { WindowType::Normal } } impl WindowType { pub(crate) fn as_atom(&self, xconn: &Arc<XConnection>) -> ffi::Atom { use self::WindowType::*; let atom_name: &[u8] = match *self { Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0", Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0", Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0", Menu => b"_NET_WM_WINDOW_TYPE_MENU\0", Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0", Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0", Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0", DropdownMenu => b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0", PopupMenu => b"_NET_WM_WINDOW_TYPE_POPUP_MENU\0", Tooltip => b"_NET_WM_WINDOW_TYPE_TOOLTIP\0", Notification => b"_NET_WM_WINDOW_TYPE_NOTIFICATION\0", Combo => b"_NET_WM_WINDOW_TYPE_COMBO\0", Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0", }; 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_ulong; // Motif WM hints are obsolete, but still widely supported. // https://stackoverflow.com/a/1909708 pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0; pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1; pub const MWM_FUNC_ALL: c_ulong = 1 << 0; pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1; pub const MWM_FUNC_MOVE: c_ulong = 1 << 2; pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3; pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4; pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5; } impl MotifHints { pub fn new() -> MotifHints { MotifHints { hints: MwmHints { flags: 0, functions: 0, decorations: 0, input_mode: 0, status: 0, }, } } pub fn set_decorations(&mut self, decorations: bool) { self.hints.flags |= mwm::MWM_HINTS_DECORATIONS; self.hints.decorations = decorations as c_ulong; } pub fn set_maximizable(&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 self.hints.functions & mwm::MWM_FUNC_ALL != 0 { self.hints.functions &= !func; } else { self.hints.functions |= func; } } } fn remove_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 { self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS; self.hints.functions = mwm::MWM_FUNC_ALL; } if self.hints.functions & mwm::MWM_FUNC_ALL != 0 { self.hints.functions |= func; } else { self.hints.functions &= !func; } } } impl MwmHints { fn as_slice(&self) -> &[c_ulong] { unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) } } } pub struct NormalHints<'a> { size_hints: XSmartPointer<'a, ffi::XSizeHints>, } impl<'a> NormalHints<'a> { pub fn new(xconn: &'a XConnection) -> Self { NormalHints { size_hints: xconn.alloc_size_hints(), } } pub fn get_position(&self) -> Option<(i32, i32)> { if has_flag(self.size_hints.flags, ffi::PPosition) { Some((self.size_hints.x as i32, self.size_hints.y as i32)) } else { None } } pub fn set_position(&mut self, position: Option<(i32, i32)>) { if let Some((x, y)) = position { self.size_hints.flags |= ffi::PPosition; self.size_hints.x = x as c_int; self.size_hints.y = y as c_int; } else { self.size_hints.flags &= !ffi::PPosition; } } // WARNING: This hint is obsolete pub fn set_size(&mut self, size: Option<(u32, u32)>) { if let Some((width, height)) = size { self.size_hints.flags |= ffi::PSize; self.size_hints.width = width as c_int; self.size_hints.height = height as c_int; } else { self.size_hints.flags &= !ffi::PSize; } } pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) { if let Some((max_width, max_height)) = max_size { self.size_hints.flags |= ffi::PMaxSize; self.size_hints.max_width = max_width as c_int; self.size_hints.max_height = max_height as c_int; } else { self.size_hints.flags &= !ffi::PMaxSize; } } pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) { if let Some((min_width, min_height)) = min_size { self.size_hints.flags |= ffi::PMinSize; self.size_hints.min_width = min_width as c_int; self.size_hints.min_height = min_height as c_int; } else { self.size_hints.flags &= !ffi::PMinSize; } } pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) { if let Some((width_inc, height_inc)) = resize_increments { self.size_hints.flags |= ffi::PResizeInc; self.size_hints.width_inc = width_inc as c_int; self.size_hints.height_inc = height_inc as c_int; } else { self.size_hints.flags &= !ffi::PResizeInc; } } pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) { if let Some((base_width, base_height)) = base_size
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) }; self
{ 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
of all other windows. Dock, /// Toolbar windows. "Torn off" from the main application. Toolbar, /// Pinnable menu windows. "Torn off" from the main application. Menu, /// A small persistent utility window, such as a palette or toolbox. Utility, /// The window is a splash screen displayed as an application is starting up. Splash, /// This is a dialog window. Dialog, /// A dropdown menu that usually appears when the user clicks on an item in a menu bar. /// This property is typically used on override-redirect windows. DropdownMenu, /// A popup menu that usually appears when the user right clicks on an object. /// This property is typically used on override-redirect windows. PopupMenu, /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor. /// This property is typically used on override-redirect windows. Tooltip, /// The window is a notification. /// This property is typically used on override-redirect windows. Notification, /// This should be used on the windows that are popped up by combo boxes. /// This property is typically used on override-redirect windows. Combo, /// This indicates the the window is being dragged. /// This property is typically used on override-redirect windows. Dnd, /// This is a normal, top-level window. Normal, } impl Default for WindowType { fn default() -> Self { WindowType::Normal } } impl WindowType { pub(crate) fn as_atom(&self, xconn: &Arc<XConnection>) -> ffi::Atom { use self::WindowType::*; let atom_name: &[u8] = match *self { Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0", Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0", Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0", Menu => b"_NET_WM_WINDOW_TYPE_MENU\0", Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0", Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0", Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0", DropdownMenu => b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0", PopupMenu => b"_NET_WM_WINDOW_TYPE_POPUP_MENU\0", Tooltip => b"_NET_WM_WINDOW_TYPE_TOOLTIP\0", Notification => b"_NET_WM_WINDOW_TYPE_NOTIFICATION\0", Combo => b"_NET_WM_WINDOW_TYPE_COMBO\0", Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0", }; 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_ulong; // Motif WM hints are obsolete, but still widely supported. // https://stackoverflow.com/a/1909708 pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0; pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1; pub const MWM_FUNC_ALL: c_ulong = 1 << 0; pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1; pub const MWM_FUNC_MOVE: c_ulong = 1 << 2; pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3; pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4; pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5; } impl MotifHints { pub fn new() -> MotifHints { MotifHints { hints: MwmHints { flags: 0, functions: 0, decorations: 0, input_mode: 0, status: 0, }, } } pub fn set_decorations(&mut self, decorations: bool) { self.hints.flags |= mwm::MWM_HINTS_DECORATIONS; self.hints.decorations = decorations as c_ulong; } pub fn
(&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 self.hints.functions & mwm::MWM_FUNC_ALL != 0 { self.hints.functions &= !func; } else { self.hints.functions |= func; } } } fn remove_func(&mut self, func: c_ulong) { if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 { self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS; self.hints.functions = mwm::MWM_FUNC_ALL; } if self.hints.functions & mwm::MWM_FUNC_ALL != 0 { self.hints.functions |= func; } else { self.hints.functions &= !func; } } } impl MwmHints { fn as_slice(&self) -> &[c_ulong] { unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) } } } pub struct NormalHints<'a> { size_hints: XSmartPointer<'a, ffi::XSizeHints>, } impl<'a> NormalHints<'a> { pub fn new(xconn: &'a XConnection) -> Self { NormalHints { size_hints: xconn.alloc_size_hints(), } } pub fn get_position(&self) -> Option<(i32, i32)> { if has_flag(self.size_hints.flags, ffi::PPosition) { Some((self.size_hints.x as i32, self.size_hints.y as i32)) } else { None } } pub fn set_position(&mut self, position: Option<(i32, i32)>) { if let Some((x, y)) = position { self.size_hints.flags |= ffi::PPosition; self.size_hints.x = x as c_int; self.size_hints.y = y as c_int; } else { self.size_hints.flags &= !ffi::PPosition; } } // WARNING: This hint is obsolete pub fn set_size(&mut self, size: Option<(u32, u32)>) { if let Some((width, height)) = size { self.size_hints.flags |= ffi::PSize; self.size_hints.width = width as c_int; self.size_hints.height = height as c_int; } else { self.size_hints.flags &= !ffi::PSize; } } pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) { if let Some((max_width, max_height)) = max_size { self.size_hints.flags |= ffi::PMaxSize; self.size_hints.max_width = max_width as c_int; self.size_hints.max_height = max_height as c_int; } else { self.size_hints.flags &= !ffi::PMaxSize; } } pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) { if let Some((min_width, min_height)) = min_size { self.size_hints.flags |= ffi::PMinSize; self.size_hints.min_width = min_width as c_int; self.size_hints.min_height = min_height as c_int; } else { self.size_hints.flags &= !ffi::PMinSize; } } pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) { if let Some((width_inc, height_inc)) = resize_increments { self.size_hints.flags |= ffi::PResizeInc; self.size_hints.width_inc = width_inc as c_int; self.size_hints.height_inc = height_inc as c_int; } else { self.size_hints.flags &= !ffi::PResizeInc; } } pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) { if let Some((base_width, base_height)) = base_size { 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; } 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) }; self
set_maximizable
identifier_name
reflection_capabilities.ts
* Attention: These regex has to hold even if the code is minified! */ export const DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/; export const INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/; export const INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/; export class ReflectionCapabilities implements PlatformReflectionCapabilities { private _reflect: any; constructor(reflect?: any) { this._reflect = reflect || global['Reflect']; } isReflectionEnabled(): boolean { return true; } factory<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 { result = new Array(paramTypes.length); } for (let i = 0; i < result.length; i++) { // TS outputs Object for parameters without types, while Traceur omits // the annotations. For now we preserve the Traceur behavior to aid // migration, but this can be revisited. if (typeof paramTypes === 'undefined') { result[i] = []; } else if (paramTypes[i] != Object) { result[i] = [paramTypes[i]]; } else { result[i] = []; } if (paramAnnotations && paramAnnotations[i] != null) { result[i] = result[i].concat(paramAnnotations[i]); } } 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 to look inside of that constructor to check whether it is // just calling the parent. // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439 // that sets 'design:paramtypes' to [] // if a class inherits from another class but has no ctor declared itself. if (DELEGATE_CTOR.exec(typeStr) || (INHERITED_CLASS.exec(typeStr) && !INHERITED_CLASS_WITH_CTOR.exec(typeStr))) { return null; } // Prefer the direct API. if ((<any>type).parameters && (<any>type).parameters !== parentCtor.parameters) { return (<any>type).parameters; } // API of tsickle for lowering decorators to properties on the class. const tsickleCtorParams = (<any>type).ctorParameters; if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) { // Newer tsickle uses a function closure // Retain the non-function case for compatibility with older tsickle const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams; const paramTypes = ctorParameters.map((ctorParam: any) => ctorParam && ctorParam.type); const paramAnnotations = ctorParameters.map( (ctorParam: any) => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators)); return this._zipTypesAndAnnotations(paramTypes, paramAnnotations); } // API for metadata created by invoking the decorators. const paramAnnotations = type.hasOwnProperty(PARAMETERS) && (type as any)[PARAMETERS]; const paramTypes = this._reflect && this._reflect.getOwnMetadata && this._reflect.getOwnMetadata('design:paramtypes', type); if (paramTypes || paramAnnotations) { return this._zipTypesAndAnnotations(paramTypes, paramAnnotations); } // If a class has no decorators, at least create metadata // based on function.length. // Note: We know that this is a real constructor as we checked // the content of the constructor above. return new Array((<any>type.length)).fill(undefined); } parameters(type: Type<any>): any[][] { // Note: only report metadata if we have at least one class decorator // to stay in sync with the static reflector. if (!isType(type)) { return []; } const parentCtor = getParentCtor(type); let parameters = this._ownParameters(type, parentCtor); if (!parameters && parentCtor !== Object) { parameters = this.parameters(parentCtor); } return parameters || []; } private _ownAnnotations(typeOrFunc: Type<any>, parentCtor: any): any[]|null { // Prefer the direct API. if ((<any>typeOrFunc).annotations && (<any>typeOrFunc).annotations !== parentCtor.annotations) { let annotations = (<any>typeOrFunc).annotations; if (typeof annotations === 'function' && annotations.annotations) { annotations = annotations.annotations; } return annotations; } // API of tsickle for lowering decorators to properties on the class. if ((<any>typeOrFunc).decorators && (<any>typeOrFunc).decorators !== parentCtor.decorators) { return convertTsickleDecoratorIntoMetadata((<any>typeOrFunc).decorators); } // API for metadata created by invoking the decorators. if (typeOrFunc.hasOwnProperty(ANNOTATIONS))
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.annotations(parentCtor) : []; return parentAnnotations.concat(ownAnnotations); } private _ownPropMetadata(typeOrFunc: any, parentCtor: any): {[key: string]: any[]}|null { // Prefer the direct API. if ((<any>typeOrFunc).propMetadata && (<any>typeOrFunc).propMetadata !== parentCtor.propMetadata) { let propMetadata = (<any>typeOrFunc).propMetadata; if (typeof propMetadata === 'function' && propMetadata.propMetadata) { propMetadata = propMetadata.propMetadata; } return propMetadata; } // API of tsickle for lowering decorators to properties on the class. if ((<any>typeOrFunc).propDecorators && (<any>typeOrFunc).propDecorators !== parentCtor.propDecorators) { const propDecorators = (<any>typeOrFunc).propDecorators; const propMetadata = <{[key: string]: any[]}>{}; Object.keys(propDecorators).forEach(prop => { propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]); }); return propMetadata; } // API for metadata created by invoking the decorators. if (typeOrFunc.hasOwnProperty(PROP_METADATA)) { return (typeOrFunc as any)[PROP_METADATA]; } return null; } propMetadata(typeOrFunc: any): {[key: string]: any[]} { if (!isType(typeOrFunc)) { return {}; } const parentCtor = getParentCtor(typeOrFunc); const propMetadata: {[key: string]: any[]} = {}; if (parentCtor !== Object) { const parentPropMetadata = this.propMetadata(parentCtor); Object.keys(parentPropMetadata).forEach((propName) => { propMetadata[propName] = parentPropMetadata[propName]; }); } const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor); if (ownPropMetadata) { Object.keys(ownPropMetadata).forEach((propName) => { const decorators: any[] = []; if (propMetadata.hasOwnProperty(propName)) { decorators.push(...propMetadata[propName]); } decorators.push(...ownPropMetadata[propName]); propMetadata[propName] = decorators; }); } return propMetadata; } hasLifecycleHook(type: any, lcProperty: string): boolean { return type instanceof Type && lcProperty in type.prototype; } guards(type: any): {[key: string]: any} { return {}; } getter(name: string): GetterFn { return <GetterFn>new Function('o', 'return o.' + name + ';'); } setter(name: string): SetterFn { return <SetterFn>new Function('o', 'v', 'return o.' + name + ' = v;'); } method(name: string): MethodFn { const functionBody = `if (!o.${name}) throw new Error('"${name}" is undefined'); return o.${name}.apply(o, args);`; return <MethodFn>new Function('o', 'args', functionBody); } // There is not a concept of import uri in Js, but this is useful in developing Dart applications
{ return (typeOrFunc as any)[ANNOTATIONS]; }
conditional_block
reflection_capabilities.ts
/** * Attention: These regex has to hold even if the code is minified! */ export const DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/; export const INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/; export const INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/; export class ReflectionCapabilities implements PlatformReflectionCapabilities { private _reflect: any; constructor(reflect?: any) { this._reflect = reflect || global['Reflect']; } isReflectionEnabled(): boolean { return true; }
<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 { result = new Array(paramTypes.length); } for (let i = 0; i < result.length; i++) { // TS outputs Object for parameters without types, while Traceur omits // the annotations. For now we preserve the Traceur behavior to aid // migration, but this can be revisited. if (typeof paramTypes === 'undefined') { result[i] = []; } else if (paramTypes[i] != Object) { result[i] = [paramTypes[i]]; } else { result[i] = []; } if (paramAnnotations && paramAnnotations[i] != null) { result[i] = result[i].concat(paramAnnotations[i]); } } 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 to look inside of that constructor to check whether it is // just calling the parent. // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439 // that sets 'design:paramtypes' to [] // if a class inherits from another class but has no ctor declared itself. if (DELEGATE_CTOR.exec(typeStr) || (INHERITED_CLASS.exec(typeStr) && !INHERITED_CLASS_WITH_CTOR.exec(typeStr))) { return null; } // Prefer the direct API. if ((<any>type).parameters && (<any>type).parameters !== parentCtor.parameters) { return (<any>type).parameters; } // API of tsickle for lowering decorators to properties on the class. const tsickleCtorParams = (<any>type).ctorParameters; if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) { // Newer tsickle uses a function closure // Retain the non-function case for compatibility with older tsickle const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams; const paramTypes = ctorParameters.map((ctorParam: any) => ctorParam && ctorParam.type); const paramAnnotations = ctorParameters.map( (ctorParam: any) => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators)); return this._zipTypesAndAnnotations(paramTypes, paramAnnotations); } // API for metadata created by invoking the decorators. const paramAnnotations = type.hasOwnProperty(PARAMETERS) && (type as any)[PARAMETERS]; const paramTypes = this._reflect && this._reflect.getOwnMetadata && this._reflect.getOwnMetadata('design:paramtypes', type); if (paramTypes || paramAnnotations) { return this._zipTypesAndAnnotations(paramTypes, paramAnnotations); } // If a class has no decorators, at least create metadata // based on function.length. // Note: We know that this is a real constructor as we checked // the content of the constructor above. return new Array((<any>type.length)).fill(undefined); } parameters(type: Type<any>): any[][] { // Note: only report metadata if we have at least one class decorator // to stay in sync with the static reflector. if (!isType(type)) { return []; } const parentCtor = getParentCtor(type); let parameters = this._ownParameters(type, parentCtor); if (!parameters && parentCtor !== Object) { parameters = this.parameters(parentCtor); } return parameters || []; } private _ownAnnotations(typeOrFunc: Type<any>, parentCtor: any): any[]|null { // Prefer the direct API. if ((<any>typeOrFunc).annotations && (<any>typeOrFunc).annotations !== parentCtor.annotations) { let annotations = (<any>typeOrFunc).annotations; if (typeof annotations === 'function' && annotations.annotations) { annotations = annotations.annotations; } return annotations; } // API of tsickle for lowering decorators to properties on the class. if ((<any>typeOrFunc).decorators && (<any>typeOrFunc).decorators !== parentCtor.decorators) { return convertTsickleDecoratorIntoMetadata((<any>typeOrFunc).decorators); } // API for metadata created by invoking the decorators. if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) { return (typeOrFunc as any)[ANNOTATIONS]; } 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.annotations(parentCtor) : []; return parentAnnotations.concat(ownAnnotations); } private _ownPropMetadata(typeOrFunc: any, parentCtor: any): {[key: string]: any[]}|null { // Prefer the direct API. if ((<any>typeOrFunc).propMetadata && (<any>typeOrFunc).propMetadata !== parentCtor.propMetadata) { let propMetadata = (<any>typeOrFunc).propMetadata; if (typeof propMetadata === 'function' && propMetadata.propMetadata) { propMetadata = propMetadata.propMetadata; } return propMetadata; } // API of tsickle for lowering decorators to properties on the class. if ((<any>typeOrFunc).propDecorators && (<any>typeOrFunc).propDecorators !== parentCtor.propDecorators) { const propDecorators = (<any>typeOrFunc).propDecorators; const propMetadata = <{[key: string]: any[]}>{}; Object.keys(propDecorators).forEach(prop => { propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]); }); return propMetadata; } // API for metadata created by invoking the decorators. if (typeOrFunc.hasOwnProperty(PROP_METADATA)) { return (typeOrFunc as any)[PROP_METADATA]; } return null; } propMetadata(typeOrFunc: any): {[key: string]: any[]} { if (!isType(typeOrFunc)) { return {}; } const parentCtor = getParentCtor(typeOrFunc); const propMetadata: {[key: string]: any[]} = {}; if (parentCtor !== Object) { const parentPropMetadata = this.propMetadata(parentCtor); Object.keys(parentPropMetadata).forEach((propName) => { propMetadata[propName] = parentPropMetadata[propName]; }); } const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor); if (ownPropMetadata) { Object.keys(ownPropMetadata).forEach((propName) => { const decorators: any[] = []; if (propMetadata.hasOwnProperty(propName)) { decorators.push(...propMetadata[propName]); } decorators.push(...ownPropMetadata[propName]); propMetadata[propName] = decorators; }); } return propMetadata; } hasLifecycleHook(type: any, lcProperty: string): boolean { return type instanceof Type && lcProperty in type.prototype; } guards(type: any): {[key: string]: any} { return {}; } getter(name: string): GetterFn { return <GetterFn>new Function('o', 'return o.' + name + ';'); } setter(name: string): SetterFn { return <SetterFn>new Function('o', 'v', 'return o.' + name + ' = v;'); } method(name: string): MethodFn { const functionBody = `if (!o.${name}) throw new Error('"${name}" is undefined'); return o.${name}.apply(o, args);`; return <MethodFn>new Function('o', 'args', functionBody); } // There is not a concept of import uri in Js, but this is useful in developing Dart applications.
factory
identifier_name
reflection_capabilities.ts
/** * Attention: These regex has to hold even if the code is minified! */ export const DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/; export const INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/; export const INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/; export class ReflectionCapabilities implements PlatformReflectionCapabilities { private _reflect: any; constructor(reflect?: any) { this._reflect = reflect || global['Reflect']; } isReflectionEnabled(): boolean { return true; } factory<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 { result = new Array(paramTypes.length); } for (let i = 0; i < result.length; i++) { // TS outputs Object for parameters without types, while Traceur omits // the annotations. For now we preserve the Traceur behavior to aid // migration, but this can be revisited. if (typeof paramTypes === 'undefined') { result[i] = []; } else if (paramTypes[i] != Object) { result[i] = [paramTypes[i]]; } else {
} 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 to look inside of that constructor to check whether it is // just calling the parent. // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439 // that sets 'design:paramtypes' to [] // if a class inherits from another class but has no ctor declared itself. if (DELEGATE_CTOR.exec(typeStr) || (INHERITED_CLASS.exec(typeStr) && !INHERITED_CLASS_WITH_CTOR.exec(typeStr))) { return null; } // Prefer the direct API. if ((<any>type).parameters && (<any>type).parameters !== parentCtor.parameters) { return (<any>type).parameters; } // API of tsickle for lowering decorators to properties on the class. const tsickleCtorParams = (<any>type).ctorParameters; if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) { // Newer tsickle uses a function closure // Retain the non-function case for compatibility with older tsickle const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams; const paramTypes = ctorParameters.map((ctorParam: any) => ctorParam && ctorParam.type); const paramAnnotations = ctorParameters.map( (ctorParam: any) => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators)); return this._zipTypesAndAnnotations(paramTypes, paramAnnotations); } // API for metadata created by invoking the decorators. const paramAnnotations = type.hasOwnProperty(PARAMETERS) && (type as any)[PARAMETERS]; const paramTypes = this._reflect && this._reflect.getOwnMetadata && this._reflect.getOwnMetadata('design:paramtypes', type); if (paramTypes || paramAnnotations) { return this._zipTypesAndAnnotations(paramTypes, paramAnnotations); } // If a class has no decorators, at least create metadata // based on function.length. // Note: We know that this is a real constructor as we checked // the content of the constructor above. return new Array((<any>type.length)).fill(undefined); } parameters(type: Type<any>): any[][] { // Note: only report metadata if we have at least one class decorator // to stay in sync with the static reflector. if (!isType(type)) { return []; } const parentCtor = getParentCtor(type); let parameters = this._ownParameters(type, parentCtor); if (!parameters && parentCtor !== Object) { parameters = this.parameters(parentCtor); } return parameters || []; } private _ownAnnotations(typeOrFunc: Type<any>, parentCtor: any): any[]|null { // Prefer the direct API. if ((<any>typeOrFunc).annotations && (<any>typeOrFunc).annotations !== parentCtor.annotations) { let annotations = (<any>typeOrFunc).annotations; if (typeof annotations === 'function' && annotations.annotations) { annotations = annotations.annotations; } return annotations; } // API of tsickle for lowering decorators to properties on the class. if ((<any>typeOrFunc).decorators && (<any>typeOrFunc).decorators !== parentCtor.decorators) { return convertTsickleDecoratorIntoMetadata((<any>typeOrFunc).decorators); } // API for metadata created by invoking the decorators. if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) { return (typeOrFunc as any)[ANNOTATIONS]; } 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.annotations(parentCtor) : []; return parentAnnotations.concat(ownAnnotations); } private _ownPropMetadata(typeOrFunc: any, parentCtor: any): {[key: string]: any[]}|null { // Prefer the direct API. if ((<any>typeOrFunc).propMetadata && (<any>typeOrFunc).propMetadata !== parentCtor.propMetadata) { let propMetadata = (<any>typeOrFunc).propMetadata; if (typeof propMetadata === 'function' && propMetadata.propMetadata) { propMetadata = propMetadata.propMetadata; } return propMetadata; } // API of tsickle for lowering decorators to properties on the class. if ((<any>typeOrFunc).propDecorators && (<any>typeOrFunc).propDecorators !== parentCtor.propDecorators) { const propDecorators = (<any>typeOrFunc).propDecorators; const propMetadata = <{[key: string]: any[]}>{}; Object.keys(propDecorators).forEach(prop => { propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]); }); return propMetadata; } // API for metadata created by invoking the decorators. if (typeOrFunc.hasOwnProperty(PROP_METADATA)) { return (typeOrFunc as any)[PROP_METADATA]; } return null; } propMetadata(typeOrFunc: any): {[key: string]: any[]} { if (!isType(typeOrFunc)) { return {}; } const parentCtor = getParentCtor(typeOrFunc); const propMetadata: {[key: string]: any[]} = {}; if (parentCtor !== Object) { const parentPropMetadata = this.propMetadata(parentCtor); Object.keys(parentPropMetadata).forEach((propName) => { propMetadata[propName] = parentPropMetadata[propName]; }); } const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor); if (ownPropMetadata) { Object.keys(ownPropMetadata).forEach((propName) => { const decorators: any[] = []; if (propMetadata.hasOwnProperty(propName)) { decorators.push(...propMetadata[propName]); } decorators.push(...ownPropMetadata[propName]); propMetadata[propName] = decorators; }); } return propMetadata; } hasLifecycleHook(type: any, lcProperty: string): boolean { return type instanceof Type && lcProperty in type.prototype; } guards(type: any): {[key: string]: any} { return {}; } getter(name: string): GetterFn { return <GetterFn>new Function('o', 'return o.' + name + ';'); } setter(name: string): SetterFn { return <SetterFn>new Function('o', 'v', 'return o.' + name + ' = v;'); } method(name: string): MethodFn { const functionBody = `if (!o.${name}) throw new Error('"${name}" is undefined'); return o.${name}.apply(o, args);`; return <MethodFn>new Function('o', 'args', functionBody); } // There is not a concept of import uri in Js, but this is useful in developing Dart applications.
result[i] = []; } if (paramAnnotations && paramAnnotations[i] != null) { result[i] = result[i].concat(paramAnnotations[i]); }
random_line_split
reflection_capabilities.ts
HERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/; export const INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/; export class ReflectionCapabilities implements PlatformReflectionCapabilities { private _reflect: any; constructor(reflect?: any) { this._reflect = reflect || global['Reflect']; } isReflectionEnabled(): boolean { return true; } factory<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 { result = new Array(paramTypes.length); } for (let i = 0; i < result.length; i++) { // TS outputs Object for parameters without types, while Traceur omits // the annotations. For now we preserve the Traceur behavior to aid // migration, but this can be revisited. if (typeof paramTypes === 'undefined') { result[i] = []; } else if (paramTypes[i] != Object) { result[i] = [paramTypes[i]]; } else { result[i] = []; } if (paramAnnotations && paramAnnotations[i] != null) { result[i] = result[i].concat(paramAnnotations[i]); } } 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 to look inside of that constructor to check whether it is // just calling the parent. // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439 // that sets 'design:paramtypes' to [] // if a class inherits from another class but has no ctor declared itself. if (DELEGATE_CTOR.exec(typeStr) || (INHERITED_CLASS.exec(typeStr) && !INHERITED_CLASS_WITH_CTOR.exec(typeStr))) { return null; } // Prefer the direct API. if ((<any>type).parameters && (<any>type).parameters !== parentCtor.parameters) { return (<any>type).parameters; } // API of tsickle for lowering decorators to properties on the class. const tsickleCtorParams = (<any>type).ctorParameters; if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) { // Newer tsickle uses a function closure // Retain the non-function case for compatibility with older tsickle const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams; const paramTypes = ctorParameters.map((ctorParam: any) => ctorParam && ctorParam.type); const paramAnnotations = ctorParameters.map( (ctorParam: any) => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators)); return this._zipTypesAndAnnotations(paramTypes, paramAnnotations); } // API for metadata created by invoking the decorators. const paramAnnotations = type.hasOwnProperty(PARAMETERS) && (type as any)[PARAMETERS]; const paramTypes = this._reflect && this._reflect.getOwnMetadata && this._reflect.getOwnMetadata('design:paramtypes', type); if (paramTypes || paramAnnotations) { return this._zipTypesAndAnnotations(paramTypes, paramAnnotations); } // If a class has no decorators, at least create metadata // based on function.length. // Note: We know that this is a real constructor as we checked // the content of the constructor above. return new Array((<any>type.length)).fill(undefined); } parameters(type: Type<any>): any[][] { // Note: only report metadata if we have at least one class decorator // to stay in sync with the static reflector. if (!isType(type)) { return []; } const parentCtor = getParentCtor(type); let parameters = this._ownParameters(type, parentCtor); if (!parameters && parentCtor !== Object) { parameters = this.parameters(parentCtor); } return parameters || []; } private _ownAnnotations(typeOrFunc: Type<any>, parentCtor: any): any[]|null { // Prefer the direct API. if ((<any>typeOrFunc).annotations && (<any>typeOrFunc).annotations !== parentCtor.annotations) { let annotations = (<any>typeOrFunc).annotations; if (typeof annotations === 'function' && annotations.annotations) { annotations = annotations.annotations; } return annotations; } // API of tsickle for lowering decorators to properties on the class. if ((<any>typeOrFunc).decorators && (<any>typeOrFunc).decorators !== parentCtor.decorators) { return convertTsickleDecoratorIntoMetadata((<any>typeOrFunc).decorators); } // API for metadata created by invoking the decorators. if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) { return (typeOrFunc as any)[ANNOTATIONS]; } 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.annotations(parentCtor) : []; return parentAnnotations.concat(ownAnnotations); } private _ownPropMetadata(typeOrFunc: any, parentCtor: any): {[key: string]: any[]}|null { // Prefer the direct API. if ((<any>typeOrFunc).propMetadata && (<any>typeOrFunc).propMetadata !== parentCtor.propMetadata) { let propMetadata = (<any>typeOrFunc).propMetadata; if (typeof propMetadata === 'function' && propMetadata.propMetadata) { propMetadata = propMetadata.propMetadata; } return propMetadata; } // API of tsickle for lowering decorators to properties on the class. if ((<any>typeOrFunc).propDecorators && (<any>typeOrFunc).propDecorators !== parentCtor.propDecorators) { const propDecorators = (<any>typeOrFunc).propDecorators; const propMetadata = <{[key: string]: any[]}>{}; Object.keys(propDecorators).forEach(prop => { propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]); }); return propMetadata; } // API for metadata created by invoking the decorators. if (typeOrFunc.hasOwnProperty(PROP_METADATA)) { return (typeOrFunc as any)[PROP_METADATA]; } return null; } propMetadata(typeOrFunc: any): {[key: string]: any[]} { if (!isType(typeOrFunc)) { return {}; } const parentCtor = getParentCtor(typeOrFunc); const propMetadata: {[key: string]: any[]} = {}; if (parentCtor !== Object) { const parentPropMetadata = this.propMetadata(parentCtor); Object.keys(parentPropMetadata).forEach((propName) => { propMetadata[propName] = parentPropMetadata[propName]; }); } const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor); if (ownPropMetadata) { Object.keys(ownPropMetadata).forEach((propName) => { const decorators: any[] = []; if (propMetadata.hasOwnProperty(propName)) { decorators.push(...propMetadata[propName]); } decorators.push(...ownPropMetadata[propName]); propMetadata[propName] = decorators; }); } return propMetadata; } hasLifecycleHook(type: any, lcProperty: string): boolean { return type instanceof Type && lcProperty in type.prototype; } guards(type: any): {[key: string]: any} { return {}; } getter(name: string): GetterFn { return <GetterFn>new Function('o', 'return o.' + name + ';'); } setter(name: string): SetterFn { return <SetterFn>new Function('o', 'v', 'return o.' + name + ' = v;'); } method(name: string): MethodFn { const functionBody = `if (!o.${name}) throw new Error('"${name}" is undefined'); return o.${name}.apply(o, args);`; return <MethodFn>new Function('o', 'args', functionBody); } // There is not a concept of import uri in Js, but this is useful in developing Dart applications. importUri(type: any): string
{ // 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_MESSAGE = "Log in with GitHub" def get_flow(redirect_url=None):
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(redirect_uri) if 'code' not in request.GET: return None code = request.GET['code'] credentials = flow.step2_exchange(code) http = httplib2.Http(".cache") http = credentials.authorize(http) (_, content) = http.request("https://api.github.com/user", "GET") response = utils.from_json(content.decode('utf-8')) user_id = response['login'] user_name = response['name'] (_, content) = http.request("https://api.github.com/user/emails", "GET") response = utils.from_json(content.decode('utf-8')) user_email = None for email in response: if email['verified'] and email['primary']: user_email = email['email'] break 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): 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_info): pass # # Election Creation # def can_create_election(user_id, user_info): return True
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_MESSAGE = "Log in with GitHub" def get_flow(redirect_url=None): 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, ) 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(redirect_uri) if 'code' not in request.GET: return None code = request.GET['code'] credentials = flow.step2_exchange(code) http = httplib2.Http(".cache") http = credentials.authorize(http) (_, content) = http.request("https://api.github.com/user", "GET") response = utils.from_json(content.decode('utf-8')) user_id = response['login'] user_name = response['name'] (_, content) = http.request("https://api.github.com/user/emails", "GET") response = utils.from_json(content.decode('utf-8')) user_email = None for email in response: if email['verified'] and email['primary']: user_email = email['email'] break 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): 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_info): pass # # Election Creation # def can_create_election(user_id, user_info): return True
}
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_MESSAGE = "Log in with GitHub" def get_flow(redirect_url=None): 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, ) 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(redirect_uri) if 'code' not in request.GET: return None code = request.GET['code'] credentials = flow.step2_exchange(code) http = httplib2.Http(".cache") http = credentials.authorize(http) (_, content) = http.request("https://api.github.com/user", "GET") response = utils.from_json(content.decode('utf-8')) user_id = response['login'] user_name = response['name'] (_, content) = http.request("https://api.github.com/user/emails", "GET") response = utils.from_json(content.decode('utf-8')) user_email = None for email in response: if email['verified'] and email['primary']: user_email = email['email'] break 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): 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_info): pass # # Election Creation # def
(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_MESSAGE = "Log in with GitHub" def get_flow(redirect_url=None): 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, ) 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(redirect_uri) if 'code' not in request.GET: return None code = request.GET['code'] credentials = flow.step2_exchange(code) http = httplib2.Http(".cache") http = credentials.authorize(http) (_, content) = http.request("https://api.github.com/user", "GET") response = utils.from_json(content.decode('utf-8')) user_id = response['login'] user_name = response['name'] (_, content) = http.request("https://api.github.com/user/emails", "GET") response = utils.from_json(content.decode('utf-8')) user_email = None for email in response: if email['verified'] and email['primary']:
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): 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_info): pass # # Election Creation # def can_create_election(user_id, user_info): return True
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. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Trie test input deserialization. use std::collections::BTreeMap; use std::str::FromStr; use bytes::Bytes; use serde::{Deserialize, Deserializer, Error}; use serde::de::{Visitor, MapVisitor, SeqVisitor}; /// Trie test input. #[derive(Debug, PartialEq)] pub struct Input { /// Input params. pub data: BTreeMap<Bytes, Option<Bytes>>, } impl Deserialize for Input { fn deserialize<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 = BTreeMap::new(); loop { let key_str: Option<String> = try!(visitor.visit_key()); let key = match key_str { Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(k) => Bytes::new(k.into_bytes()), None => { break; } }; let val_str: Option<String> = try!(visitor.visit_value()); let val = match val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(v) => Some(Bytes::new(v.into_bytes())), None => None, }; result.insert(key, val); } try!(visitor.end()); let input = Input { data: result }; Ok(input) } fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: SeqVisitor { let mut result = BTreeMap::new(); loop { let keyval: Option<Vec<Option<String>>> = try!(visitor.visit()); let keyval = match keyval { Some(k) => k, _ => { break; }, }; if keyval.len() != 2
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 = match *val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(ref v) => Some(Bytes::new(v.clone().into_bytes())), None => None, }; result.insert(key, val); } 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" : null }"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } #[test] fn input_deserialization_from_array() { let s = r#"[ ["0x0045", "0x0123456789"], ["be", "e"], ["0x0a", null] ]"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } }
{ 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. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Trie test input deserialization. use std::collections::BTreeMap; use std::str::FromStr; use bytes::Bytes; use serde::{Deserialize, Deserializer, Error}; use serde::de::{Visitor, MapVisitor, SeqVisitor}; /// Trie test input. #[derive(Debug, PartialEq)] pub struct Input { /// Input params. pub data: BTreeMap<Bytes, Option<Bytes>>, } impl Deserialize for Input { fn
<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 = BTreeMap::new(); loop { let key_str: Option<String> = try!(visitor.visit_key()); let key = match key_str { Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(k) => Bytes::new(k.into_bytes()), None => { break; } }; let val_str: Option<String> = try!(visitor.visit_value()); let val = match val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(v) => Some(Bytes::new(v.into_bytes())), None => None, }; result.insert(key, val); } try!(visitor.end()); let input = Input { data: result }; Ok(input) } fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: SeqVisitor { let mut result = BTreeMap::new(); loop { let keyval: Option<Vec<Option<String>>> = try!(visitor.visit()); let keyval = match keyval { Some(k) => k, _ => { break; }, }; if keyval.len() != 2 { return Err(Error::custom("Invalid key value pair.")); } 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 = match *val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(ref v) => Some(Bytes::new(v.clone().into_bytes())), None => None, }; result.insert(key, val); } 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" : null }"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } #[test] fn input_deserialization_from_array() { let s = r#"[ ["0x0045", "0x0123456789"], ["be", "e"], ["0x0a", null] ]"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } }
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. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Trie test input deserialization. use std::collections::BTreeMap; use std::str::FromStr; use bytes::Bytes; use serde::{Deserialize, Deserializer, Error}; use serde::de::{Visitor, MapVisitor, SeqVisitor}; /// Trie test input. #[derive(Debug, PartialEq)] pub struct Input { /// Input params. pub data: BTreeMap<Bytes, Option<Bytes>>, } impl Deserialize for Input { fn deserialize<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 = BTreeMap::new(); loop { let key_str: Option<String> = try!(visitor.visit_key()); let key = match key_str { Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(k) => Bytes::new(k.into_bytes()), None => { break; } }; let val_str: Option<String> = try!(visitor.visit_value()); let val = match val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(v) => Some(Bytes::new(v.into_bytes())), None => None, }; result.insert(key, val); } try!(visitor.end()); let input = Input { data: result }; Ok(input) } fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: SeqVisitor { let mut result = BTreeMap::new(); loop { let keyval: Option<Vec<Option<String>>> = try!(visitor.visit()); let keyval = match keyval { Some(k) => k, _ => { break; }, }; if keyval.len() != 2 { return Err(Error::custom("Invalid key value pair.")); } 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 = match *val_str { Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(ref v) => Some(Bytes::new(v.clone().into_bytes())), None => None,
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" : null }"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } #[test] fn input_deserialization_from_array() { let s = r#"[ ["0x0045", "0x0123456789"], ["be", "e"], ["0x0a", null] ]"#; let input: Input = serde_json::from_str(s).unwrap(); let mut map = BTreeMap::new(); map.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89]))); map.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65]))); map.insert(Bytes::new(vec![0x0a]), None); assert_eq!(input.data, map); } }
}; 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_name'] = OS_CHOICES[env.os] env['install_path'] = getattr(env, 'install_path', DEFAULT_INSTALL_PATH[env.os]) env['virtualenv_name'] = getattr(env, 'virtualenv_name', DEFAULT_VIRTUALENV_NAME[env.os]) env['repository_name'] = getattr(env, 'repository_name', DEFAULT_REPOSITORY_NAME[env.os]) env['virtualenv_path'] = os.path.join(env.install_path, env.virtualenv_name) env['repository_path'] = os.path.join(env.virtualenv_path, env.repository_name) env['database_manager'] = getattr(env, 'database_manager', DEFAULT_DATABASE_MANAGER) env['database_manager_name'] = DB_CHOICES[env.database_manager] env['database_username'] = getattr(env, 'database_username', DEFAULT_DATABASE_USERNAME) env['database_password'] = getattr(env, 'database_password', password_generator()) env['database_host'] = getattr(env, 'database_host', DEFAULT_DATABASE_HOST) env['drop_database'] = getattr(env, 'drop_database', False) if not getattr(env, 'database_manager_admin_password', None): print('Must set the database_manager_admin_password entry in the fabric settings file (~/.fabricrc by default)') exit(1) 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('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\'' % (dict(WEB_CHOICES).keys(), green(DEFAULT_WEBSERVER))) print('\n')
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_CHOICES, DEFAULT_DATABASE_USERNAME, DJANGO_DB_DRIVERS, DEFAULT_DATABASE_HOST, DEFAULT_PASSWORD_LENGTH) from server_config import reduce_env def
(): # 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.os] env['install_path'] = getattr(env, 'install_path', DEFAULT_INSTALL_PATH[env.os]) env['virtualenv_name'] = getattr(env, 'virtualenv_name', DEFAULT_VIRTUALENV_NAME[env.os]) env['repository_name'] = getattr(env, 'repository_name', DEFAULT_REPOSITORY_NAME[env.os]) env['virtualenv_path'] = os.path.join(env.install_path, env.virtualenv_name) env['repository_path'] = os.path.join(env.virtualenv_path, env.repository_name) env['database_manager'] = getattr(env, 'database_manager', DEFAULT_DATABASE_MANAGER) env['database_manager_name'] = DB_CHOICES[env.database_manager] env['database_username'] = getattr(env, 'database_username', DEFAULT_DATABASE_USERNAME) env['database_password'] = getattr(env, 'database_password', password_generator()) env['database_host'] = getattr(env, 'database_host', DEFAULT_DATABASE_HOST) env['drop_database'] = getattr(env, 'drop_database', False) if not getattr(env, 'database_manager_admin_password', None): print('Must set the database_manager_admin_password entry in the fabric settings file (~/.fabricrc by default)') exit(1) 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('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\'' % (dict(WEB_CHOICES).keys(), green(DEFAULT_WEBSERVER))) print('\n')
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_CHOICES, DEFAULT_DATABASE_USERNAME, DJANGO_DB_DRIVERS, DEFAULT_DATABASE_HOST, DEFAULT_PASSWORD_LENGTH) from server_config import reduce_env 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_name'] = OS_CHOICES[env.os] env['install_path'] = getattr(env, 'install_path', DEFAULT_INSTALL_PATH[env.os]) env['virtualenv_name'] = getattr(env, 'virtualenv_name', DEFAULT_VIRTUALENV_NAME[env.os]) env['repository_name'] = getattr(env, 'repository_name', DEFAULT_REPOSITORY_NAME[env.os]) env['virtualenv_path'] = os.path.join(env.install_path, env.virtualenv_name) env['repository_path'] = os.path.join(env.virtualenv_path, env.repository_name) env['database_manager'] = getattr(env, 'database_manager', DEFAULT_DATABASE_MANAGER) env['database_manager_name'] = DB_CHOICES[env.database_manager] env['database_username'] = getattr(env, 'database_username', DEFAULT_DATABASE_USERNAME) env['database_password'] = getattr(env, 'database_password', password_generator()) env['database_host'] = getattr(env, 'database_host', DEFAULT_DATABASE_HOST) env['drop_database'] = getattr(env, 'drop_database', False) if not getattr(env, 'database_manager_admin_password', None):
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('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\'' % (dict(WEB_CHOICES).keys(), green(DEFAULT_WEBSERVER))) print('\n')
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_CHOICES, DEFAULT_DATABASE_USERNAME, DJANGO_DB_DRIVERS, DEFAULT_DATABASE_HOST, DEFAULT_PASSWORD_LENGTH) from server_config import reduce_env 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_name'] = OS_CHOICES[env.os] env['install_path'] = getattr(env, 'install_path', DEFAULT_INSTALL_PATH[env.os]) env['virtualenv_name'] = getattr(env, 'virtualenv_name', DEFAULT_VIRTUALENV_NAME[env.os]) env['repository_name'] = getattr(env, 'repository_name', DEFAULT_REPOSITORY_NAME[env.os]) env['virtualenv_path'] = os.path.join(env.install_path, env.virtualenv_name) env['repository_path'] = os.path.join(env.virtualenv_path, env.repository_name) env['database_manager'] = getattr(env, 'database_manager', DEFAULT_DATABASE_MANAGER) env['database_manager_name'] = DB_CHOICES[env.database_manager] env['database_username'] = getattr(env, 'database_username', DEFAULT_DATABASE_USERNAME) env['database_password'] = getattr(env, 'database_password', password_generator()) env['database_host'] = getattr(env, 'database_host', DEFAULT_DATABASE_HOST) env['drop_database'] = getattr(env, 'drop_database', False) if not getattr(env, 'database_manager_admin_password', None): print('Must set the database_manager_admin_password entry in the fabric settings file (~/.fabricrc by default)') exit(1) 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('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\'' % (dict(WEB_CHOICES).keys(), green(DEFAULT_WEBSERVER))) print('\n')
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::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::cssstylesheet::CSSStyleSheet; use dom::document::Document; use dom::element::{Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node}; use dom::stylesheet::StyleSheet as DOMStyleSheet; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::cell::Cell; use style::media_queries::parse_media_query_list; use style::parser::ParserContext as CssParserContext; use style::stylesheets::{CssRuleType, Stylesheet, Origin}; use style_traits::PARSING_MODE_DEFAULT; use stylesheet_loader::{StylesheetLoader, StylesheetOwner}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, in_stack_of_open_elements: Cell<bool>, pending_loads: Cell<u32>,
impl HTMLStyleElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), parser_inserted: Cell::new(creator.is_parser_created()), in_stack_of_open_elements: Cell::new(creator.is_parser_created()), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), line_number: creator.return_line_number(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> DomRoot<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let window = window_from_node(node); let doc = document_from_node(self); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let url = window.get_url(); let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media), PARSING_MODE_DEFAULT, doc.quirks_mode()); let shared_lock = node.owner_doc().style_shared_lock().clone(); let mut input = ParserInput::new(&mq_str); let css_error_reporter = window.css_error_reporter(); let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context, &mut CssParser::new(&mut input), css_error_reporter))); let loader = StylesheetLoader::for_element(self.upcast()); let sheet = Stylesheet::from_str(&data, window.get_url(), Origin::Author, mq, shared_lock, Some(&loader), css_error_reporter, doc.quirks_mode(), self.line_number as u32); let sheet = Arc::new(sheet); // No subresource loads were triggered, just fire the load event now. if self.pending_loads.get() == 0 { self.upcast::<EventTarget>().fire_event(atom!("load")); } self.set_stylesheet(sheet); } // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new(&window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet) }) }) } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { self.super_type().unwrap().children_changed(mutation); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and one of its child nodes is modified by a script." // TODO: Handle Text child contents being mutated. if self.upcast::<Node>().is_in_doc() && !self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and it becomes connected or disconnected." if tree_in_doc && !self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn pop(&self) { self.super_type().unwrap().pop(); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is popped off the stack of open elements of an HTML parser or XML parser." self.in_stack_of_open_elements.set(false); if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if context.tree_in_doc { if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s) } } } } impl StylesheetOwner for HTMLStyleElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&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; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
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::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::cssstylesheet::CSSStyleSheet; use dom::document::Document; use dom::element::{Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node}; use dom::stylesheet::StyleSheet as DOMStyleSheet; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::cell::Cell; use style::media_queries::parse_media_query_list; use style::parser::ParserContext as CssParserContext; use style::stylesheets::{CssRuleType, Stylesheet, Origin}; use style_traits::PARSING_MODE_DEFAULT; use stylesheet_loader::{StylesheetLoader, StylesheetOwner}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, in_stack_of_open_elements: Cell<bool>, pending_loads: Cell<u32>, any_failed_load: Cell<bool>, line_number: u64, } impl HTMLStyleElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), parser_inserted: Cell::new(creator.is_parser_created()), in_stack_of_open_elements: Cell::new(creator.is_parser_created()), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), line_number: creator.return_line_number(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> DomRoot<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let window = window_from_node(node); let doc = document_from_node(self); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let url = window.get_url(); let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media), PARSING_MODE_DEFAULT, doc.quirks_mode()); let shared_lock = node.owner_doc().style_shared_lock().clone(); let mut input = ParserInput::new(&mq_str); let css_error_reporter = window.css_error_reporter(); let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context, &mut CssParser::new(&mut input), css_error_reporter))); let loader = StylesheetLoader::for_element(self.upcast()); let sheet = Stylesheet::from_str(&data, window.get_url(), Origin::Author, mq, shared_lock, Some(&loader), css_error_reporter, doc.quirks_mode(), self.line_number as u32); let sheet = Arc::new(sheet); // No subresource loads were triggered, just fire the load event now. if self.pending_loads.get() == 0 { self.upcast::<EventTarget>().fire_event(atom!("load")); } self.set_stylesheet(sheet); } // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new(&window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet) }) }) } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { self.super_type().unwrap().children_changed(mutation); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and one of its child nodes is modified by a script." // TODO: Handle Text child contents being mutated. if self.upcast::<Node>().is_in_doc() && !self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and it becomes connected or disconnected." if tree_in_doc && !self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn pop(&self) { self.super_type().unwrap().pop(); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is popped off the stack of open elements of an HTML parser or XML parser." self.in_stack_of_open_elements.set(false); if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if context.tree_in_doc { if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s) } } } } impl StylesheetOwner for HTMLStyleElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn
(&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; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
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::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::cssstylesheet::CSSStyleSheet; use dom::document::Document; use dom::element::{Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node}; use dom::stylesheet::StyleSheet as DOMStyleSheet; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::cell::Cell; use style::media_queries::parse_media_query_list; use style::parser::ParserContext as CssParserContext; use style::stylesheets::{CssRuleType, Stylesheet, Origin}; use style_traits::PARSING_MODE_DEFAULT; use stylesheet_loader::{StylesheetLoader, StylesheetOwner}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, in_stack_of_open_elements: Cell<bool>, pending_loads: Cell<u32>, any_failed_load: Cell<bool>, line_number: u64, } impl HTMLStyleElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), parser_inserted: Cell::new(creator.is_parser_created()), in_stack_of_open_elements: Cell::new(creator.is_parser_created()), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), line_number: creator.return_line_number(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> DomRoot<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let window = window_from_node(node); let doc = document_from_node(self); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let url = window.get_url(); let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media), PARSING_MODE_DEFAULT, doc.quirks_mode()); let shared_lock = node.owner_doc().style_shared_lock().clone(); let mut input = ParserInput::new(&mq_str); let css_error_reporter = window.css_error_reporter(); let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context, &mut CssParser::new(&mut input), css_error_reporter))); let loader = StylesheetLoader::for_element(self.upcast()); let sheet = Stylesheet::from_str(&data, window.get_url(), Origin::Author, mq, shared_lock, Some(&loader), css_error_reporter, doc.quirks_mode(), self.line_number as u32); let sheet = Arc::new(sheet); // No subresource loads were triggered, just fire the load event now. if self.pending_loads.get() == 0 { self.upcast::<EventTarget>().fire_event(atom!("load")); } self.set_stylesheet(sheet); } // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new(&window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet) }) }) } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { self.super_type().unwrap().children_changed(mutation); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and one of its child nodes is modified by a script." // TODO: Handle Text child contents being mutated. if self.upcast::<Node>().is_in_doc() && !self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and it becomes connected or disconnected." if tree_in_doc && !self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn pop(&self) { self.super_type().unwrap().pop(); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is popped off the stack of open elements of an HTML parser or XML parser." self.in_stack_of_open_elements.set(false); if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if context.tree_in_doc { if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s) } } } } impl StylesheetOwner for HTMLStyleElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&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; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>>
}
{ 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::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::cssstylesheet::CSSStyleSheet; use dom::document::Document; use dom::element::{Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node}; use dom::stylesheet::StyleSheet as DOMStyleSheet; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::cell::Cell; use style::media_queries::parse_media_query_list; use style::parser::ParserContext as CssParserContext; use style::stylesheets::{CssRuleType, Stylesheet, Origin}; use style_traits::PARSING_MODE_DEFAULT; use stylesheet_loader::{StylesheetLoader, StylesheetOwner}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, in_stack_of_open_elements: Cell<bool>, pending_loads: Cell<u32>, any_failed_load: Cell<bool>, line_number: u64, } impl HTMLStyleElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), parser_inserted: Cell::new(creator.is_parser_created()), in_stack_of_open_elements: Cell::new(creator.is_parser_created()), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), line_number: creator.return_line_number(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> DomRoot<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let window = window_from_node(node); let doc = document_from_node(self); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let url = window.get_url(); let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media), PARSING_MODE_DEFAULT, doc.quirks_mode()); let shared_lock = node.owner_doc().style_shared_lock().clone(); let mut input = ParserInput::new(&mq_str); let css_error_reporter = window.css_error_reporter(); let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context, &mut CssParser::new(&mut input), css_error_reporter))); let loader = StylesheetLoader::for_element(self.upcast()); let sheet = Stylesheet::from_str(&data, window.get_url(), Origin::Author, mq, shared_lock, Some(&loader), css_error_reporter, doc.quirks_mode(), self.line_number as u32); let sheet = Arc::new(sheet); // No subresource loads were triggered, just fire the load event now. if self.pending_loads.get() == 0 { self.upcast::<EventTarget>().fire_event(atom!("load")); } self.set_stylesheet(sheet); } // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new(&window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet) }) }) } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { self.super_type().unwrap().children_changed(mutation); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and one of its child nodes is modified by a script." // TODO: Handle Text child contents being mutated. if self.upcast::<Node>().is_in_doc() && !self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and it becomes connected or disconnected." if tree_in_doc && !self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn pop(&self) { self.super_type().unwrap().pop(); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is popped off the stack of open elements of an HTML parser or XML parser." self.in_stack_of_open_elements.set(false); if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if context.tree_in_doc { if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s) } } } } impl StylesheetOwner for HTMLStyleElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if !succeeded
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 { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
{ 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", () => { let connections: Connection[]; before(async () => connections = await createTestingConnections({ entities: [PostEntity], })); beforeEach(() => reloadTestingDatabases(connections)); after(() => closeTestingConnections(connections)); it("should create instance of the target", () => Promise.all(connections.map(async connection => { const postRepository = connection.getRepository(Post); const post = postRepository.create({ title: "First Post", text: "About first post", }); post.should.be.instanceof(Post); }))); it("should find instances of the target", () => Promise.all(connections.map(async connection => { const postRepository = connection.getRepository(Post); const post = new Post(); post.title = "First Post"; post.text = "About first post"; await postRepository.save(post); const loadedPost = await postRepository.findOne({ title: "First Post" }); loadedPost!.should.be.instanceof(Post); })));
});
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 settings from django.utils import six from django import forms from django.forms import widgets, MultiWidget, Media from django.utils.html import conditional_escape, format_html, format_html_join from django.forms.util import flatatt, to_current_timezone from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from django.templatetags.static import static from . import LatLng # classe widget utilizzata dal campo forms.geoFields LatLngField class LatLngTextInputWidget(forms.MultiWidget): def __init__(self, attrs=None): widgets = ( forms.TextInput(), forms.TextInput(), ) super(LatLngTextInputWidget, self).__init__(widgets, attrs) def decompress(self, value): if isinstance(value, six.text_type):
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': _("latitude"), }, 'longitude': { 'html': rendered_widgets[1], 'label': _("longitude"), }, 'config': { 'map_widget_height': settings.GEOPOSITIONMAP_MAP_WIDGET_HEIGHT, 'map_options': json.dumps(settings.GEOPOSITIONMAP_MAP_OPTIONS), 'marker_options': json.dumps(settings.GEOPOSITIONMAP_MARKER_OPTIONS), 'google_view': json.dumps(settings.GEOPOSITIONMAP_GOOGLE_VIEW), 'osm_view': json.dumps(settings.GEOPOSITIONMAP_OSM_VIEW), } }) class Media: #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.leafletjs.com/leaflet-0.7.3/leaflet.js', 'geopositionmap/geopositionmap.js', )
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 settings from django.utils import six from django import forms from django.forms import widgets, MultiWidget, Media from django.utils.html import conditional_escape, format_html, format_html_join from django.forms.util import flatatt, to_current_timezone from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from django.templatetags.static import static from . import LatLng # classe widget utilizzata dal campo forms.geoFields LatLngField class LatLngTextInputWidget(forms.MultiWidget): def __init__(self, attrs=None): widgets = ( forms.TextInput(), forms.TextInput(), ) super(LatLngTextInputWidget, self).__init__(widgets, attrs) 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/widgets/geopositionmap.html', { 'latitude': { 'html': rendered_widgets[0], 'label': _("latitude"), }, 'longitude': { 'html': rendered_widgets[1], 'label': _("longitude"), }, 'config': { 'map_widget_height': settings.GEOPOSITIONMAP_MAP_WIDGET_HEIGHT, 'map_options': json.dumps(settings.GEOPOSITIONMAP_MAP_OPTIONS), 'marker_options': json.dumps(settings.GEOPOSITIONMAP_MARKER_OPTIONS), 'google_view': json.dumps(settings.GEOPOSITIONMAP_GOOGLE_VIEW), 'osm_view': json.dumps(settings.GEOPOSITIONMAP_OSM_VIEW), } }) class Media: #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.leafletjs.com/leaflet-0.7.3/leaflet.js', 'geopositionmap/geopositionmap.js',
)
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 settings from django.utils import six from django import forms from django.forms import widgets, MultiWidget, Media from django.utils.html import conditional_escape, format_html, format_html_join from django.forms.util import flatatt, to_current_timezone from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from django.templatetags.static import static from . import LatLng # classe widget utilizzata dal campo forms.geoFields LatLngField class LatLngTextInputWidget(forms.MultiWidget): def __init__(self, attrs=None): widgets = ( forms.TextInput(), forms.TextInput(), ) super(LatLngTextInputWidget, self).__init__(widgets, attrs) 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/widgets/geopositionmap.html', { 'latitude': { 'html': rendered_widgets[0], 'label': _("latitude"), }, 'longitude': { 'html': rendered_widgets[1], 'label': _("longitude"), }, 'config': { 'map_widget_height': settings.GEOPOSITIONMAP_MAP_WIDGET_HEIGHT, 'map_options': json.dumps(settings.GEOPOSITIONMAP_MAP_OPTIONS), 'marker_options': json.dumps(settings.GEOPOSITIONMAP_MARKER_OPTIONS), 'google_view': json.dumps(settings.GEOPOSITIONMAP_GOOGLE_VIEW), 'osm_view': json.dumps(settings.GEOPOSITIONMAP_OSM_VIEW), } }) class
: #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.leafletjs.com/leaflet-0.7.3/leaflet.js', 'geopositionmap/geopositionmap.js', )
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 settings from django.utils import six from django import forms from django.forms import widgets, MultiWidget, Media from django.utils.html import conditional_escape, format_html, format_html_join from django.forms.util import flatatt, to_current_timezone from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from django.templatetags.static import static from . import LatLng # classe widget utilizzata dal campo forms.geoFields LatLngField class LatLngTextInputWidget(forms.MultiWidget): def __init__(self, attrs=None):
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/widgets/geopositionmap.html', { 'latitude': { 'html': rendered_widgets[0], 'label': _("latitude"), }, 'longitude': { 'html': rendered_widgets[1], 'label': _("longitude"), }, 'config': { 'map_widget_height': settings.GEOPOSITIONMAP_MAP_WIDGET_HEIGHT, 'map_options': json.dumps(settings.GEOPOSITIONMAP_MAP_OPTIONS), 'marker_options': json.dumps(settings.GEOPOSITIONMAP_MARKER_OPTIONS), 'google_view': json.dumps(settings.GEOPOSITIONMAP_GOOGLE_VIEW), 'osm_view': json.dumps(settings.GEOPOSITIONMAP_OSM_VIEW), } }) class Media: #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.leafletjs.com/leaflet-0.7.3/leaflet.js', 'geopositionmap/geopositionmap.js', )
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-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 #![allow(unknown_features)] #![feature(box_syntax)] // This is a regression test that the metadata for the // name_pool::methods impl in the other crate is reachable from this // crate. // 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()); }
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-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 #![allow(unknown_features)] #![feature(box_syntax)]
// 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-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 #![allow(unknown_features)] #![feature(box_syntax)] // This is a regression test that the metadata for the // name_pool::methods impl in the other crate is reachable from this // crate. // aux-build:crate-method-reexport-grrrrrrr2.rs extern crate crate_method_reexport_grrrrrrr2; pub fn
() { 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 may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class
(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 certificate_type: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'certificate_type': {'key': 'cty', 'type': 'str'}, } def __init__(self, name=None, certificate_type=None): self.name = name self.certificate_type = certificate_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 may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model 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 issuer provider. :type certificate_type: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'certificate_type': {'key': 'cty', 'type': 'str'}, } def __init__(self, name=None, certificate_type=None):
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 may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model
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 issuer provider. :type certificate_type: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'certificate_type': {'key': 'cty', 'type': 'str'}, } def __init__(self, name=None, certificate_type=None): self.name = name self.certificate_type = certificate_type
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_package/dummy.py") if sys.version_info[0] == 3: # Python3 specific: # To import pyc modules, we must move them out of the __pycache__ # directory and rename them to remove ".cpython-%s%d" # see: http://stackoverflow.com/questions/11648440/python-does-not-detect-pyc-files for f in os.listdir("dummy_package/__pycache__"): dst = f.replace('.cpython-%s%s' % sys.version_info[:2], "") dst = os.path.join("dummy_package", dst) shutil.copy(os.path.join("dummy_package/__pycache__", f), dst) @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_package") if __name__ == "__main__": test_pyc()
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
(): 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: # To import pyc modules, we must move them out of the __pycache__ # directory and rename them to remove ".cpython-%s%d" # see: http://stackoverflow.com/questions/11648440/python-does-not-detect-pyc-files for f in os.listdir("dummy_package/__pycache__"): dst = f.replace('.cpython-%s%s' % sys.version_info[:2], "") dst = os.path.join("dummy_package", dst) shutil.copy(os.path.join("dummy_package/__pycache__", f), dst) @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_package") if __name__ == "__main__": test_pyc()
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: 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_package/dummy.py") if sys.version_info[0] == 3: # Python3 specific: # To import pyc modules, we must move them out of the __pycache__ # directory and rename them to remove ".cpython-%s%d" # see: http://stackoverflow.com/questions/11648440/python-does-not-detect-pyc-files for f in os.listdir("dummy_package/__pycache__"): dst = f.replace('.cpython-%s%s' % sys.version_info[:2], "") dst = os.path.join("dummy_package", dst) shutil.copy(os.path.join("dummy_package/__pycache__", f), dst) @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_package") if __name__ == "__main__":
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: pass class Bar: pass """ def generate_pyc():
@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_package") if __name__ == "__main__": test_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_package/dummy.py") if sys.version_info[0] == 3: # Python3 specific: # To import pyc modules, we must move them out of the __pycache__ # directory and rename them to remove ".cpython-%s%d" # see: http://stackoverflow.com/questions/11648440/python-does-not-detect-pyc-files for f in os.listdir("dummy_package/__pycache__"): dst = f.replace('.cpython-%s%s' % sys.version_info[:2], "") dst = os.path.join("dummy_package", dst) shutil.copy(os.path.join("dummy_package/__pycache__", f), dst)
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, initialAdmins: [], }, }); expect(wrapper.find('.empty-table-message').text()).toBe( T.courseEditAdminsEmpty, ); }); it('Should handle runs', async () => { const wrapper = shallowMount(common_Admins, {
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' }, ], }, }); expect(wrapper.find('table tbody').text()).toContain('owner'); await wrapper.find('input[name="toggle-site-admins"]').trigger('click'); expect(wrapper.find('table tbody').text()).toContain('site-admin'); }); });
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 from './AppNavigator'; import ProgressBar from './components/loaders/ProgressBar'; import theme from './themes/base-theme';
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, marginBottom: 10, justifyContent: 'center' }, modal: { justifyContent: 'center', alignItems: 'center' }, modal1: { height: 300, width: 300 } }); class App extends Component { constructor(props) { super(props); this.state = { showDownloadingModal: false, showInstalling: false, downloadProgress: 0 } } componentDidMount() { CodePush.sync({ updateDialog: true, installMode: CodePush.InstallMode.IMMEDIATE }, (status) => { switch (status) { case CodePush.SyncStatus.DOWNLOADING_PACKAGE: this.setState({showDownloadingModal: true}); this.refs.modal.open(); break; case CodePush.SyncStatus.INSTALLING_UPDATE: this.setState({showInstalling: true}); break; case CodePush.SyncStatus.UPDATE_INSTALLED: this.refs.modal.close(); this.setState({showDownloadingModal: false}); break; } }, ({ receivedBytes, totalBytes, }) => { this.setState({downloadProgress: receivedBytes / totalBytes * 100}); } ); } render() { if(this.state.showDownloadingModal) return ( <View style={{backgroundColor: theme.brandSecondary}}> <InputGroup borderType='rounded' > <Icon name='ios-person-outline' /> <Input placeholder='Username' /> </InputGroup> <InputGroup borderType='rounded' > <Icon name='ios-unlock-outline' /> <Input placeholder='Password' secureTextEntry={true} /> </InputGroup> </View> ); else return( <AppNavigator store={this.props.store} /> ); } } export default App
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 from './AppNavigator'; import ProgressBar from './components/loaders/ProgressBar'; import theme from './themes/base-theme'; 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, marginBottom: 10, justifyContent: 'center' }, modal: { justifyContent: 'center', alignItems: 'center' }, modal1: { height: 300, width: 300 } }); class App extends Component { constructor(props) { super(props); this.state = { showDownloadingModal: false, showInstalling: false, downloadProgress: 0 } } componentDidMount() { CodePush.sync({ updateDialog: true, installMode: CodePush.InstallMode.IMMEDIATE }, (status) => { switch (status) { case CodePush.SyncStatus.DOWNLOADING_PACKAGE: this.setState({showDownloadingModal: true}); this.refs.modal.open(); break; case CodePush.SyncStatus.INSTALLING_UPDATE: this.setState({showInstalling: true}); break; case CodePush.SyncStatus.UPDATE_INSTALLED: this.refs.modal.close(); this.setState({showDownloadingModal: false}); break; } }, ({ receivedBytes, totalBytes, }) => { this.setState({downloadProgress: receivedBytes / totalBytes * 100}); } ); }
() { if(this.state.showDownloadingModal) return ( <View style={{backgroundColor: theme.brandSecondary}}> <InputGroup borderType='rounded' > <Icon name='ios-person-outline' /> <Input placeholder='Username' /> </InputGroup> <InputGroup borderType='rounded' > <Icon name='ios-unlock-outline' /> <Input placeholder='Password' secureTextEntry={true} /> </InputGroup> </View> ); else return( <AppNavigator store={this.props.store} /> ); } } export default App
render
identifier_name