file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
page_visibility.ts
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; /** * Specifies page visibility based on incognito status and Chrome OS guest mode. */ export type PageVisibility = {
appearance?: boolean|AppearancePageVisibility, autofill?: boolean, defaultBrowser?: boolean, downloads?: boolean, extensions?: boolean, languages?: boolean, onStartup?: boolean, people?: boolean, privacy?: boolean|PrivacyPageVisibility, reset?: boolean, safetyCheck?: boolean, }; export type AppearancePageVisibility = { bookmarksBar: boolean, homeButton: boolean, pageZoom: boolean, setTheme: boolean, }; export type PrivacyPageVisibility = { networkPrediction: boolean, searchPrediction: boolean, }; /** * Dictionary defining page visibility. */ export let pageVisibility: PageVisibility; if (loadTimeData.getBoolean('isGuest')) { // "if not chromeos" and "if chromeos" in two completely separate blocks // to work around closure compiler. // <if expr="not (chromeos_ash or chromeos_lacros)"> pageVisibility = { autofill: false, people: false, privacy: false, onStartup: false, reset: false, safetyCheck: false, appearance: false, defaultBrowser: false, advancedSettings: false, extensions: false, languages: false, }; // </if> // <if expr="chromeos_ash or chromeos_lacros"> pageVisibility = { autofill: false, people: false, onStartup: false, reset: false, safetyCheck: false, appearance: { setTheme: false, homeButton: false, bookmarksBar: false, pageZoom: false, }, advancedSettings: true, privacy: { searchPrediction: false, networkPrediction: false, }, downloads: true, a11y: true, extensions: false, languages: true, }; // </if> } else { // All pages are visible when not in chromeos. Since polymer only notifies // after a property is set. // <if expr="chromeos"> pageVisibility = { autofill: true, people: true, onStartup: true, reset: true, safetyCheck: true, appearance: { setTheme: true, homeButton: true, bookmarksBar: true, pageZoom: true, }, advancedSettings: true, privacy: { searchPrediction: true, networkPrediction: true, }, downloads: true, a11y: true, extensions: true, languages: true, }; // </if> } export function setPageVisibilityForTesting(testVisibility: PageVisibility) { pageVisibility = testVisibility; }
a11y?: boolean, advancedSettings?: boolean,
random_line_split
page_visibility.ts
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; /** * Specifies page visibility based on incognito status and Chrome OS guest mode. */ export type PageVisibility = { a11y?: boolean, advancedSettings?: boolean, appearance?: boolean|AppearancePageVisibility, autofill?: boolean, defaultBrowser?: boolean, downloads?: boolean, extensions?: boolean, languages?: boolean, onStartup?: boolean, people?: boolean, privacy?: boolean|PrivacyPageVisibility, reset?: boolean, safetyCheck?: boolean, }; export type AppearancePageVisibility = { bookmarksBar: boolean, homeButton: boolean, pageZoom: boolean, setTheme: boolean, }; export type PrivacyPageVisibility = { networkPrediction: boolean, searchPrediction: boolean, }; /** * Dictionary defining page visibility. */ export let pageVisibility: PageVisibility; if (loadTimeData.getBoolean('isGuest')) { // "if not chromeos" and "if chromeos" in two completely separate blocks // to work around closure compiler. // <if expr="not (chromeos_ash or chromeos_lacros)"> pageVisibility = { autofill: false, people: false, privacy: false, onStartup: false, reset: false, safetyCheck: false, appearance: false, defaultBrowser: false, advancedSettings: false, extensions: false, languages: false, }; // </if> // <if expr="chromeos_ash or chromeos_lacros"> pageVisibility = { autofill: false, people: false, onStartup: false, reset: false, safetyCheck: false, appearance: { setTheme: false, homeButton: false, bookmarksBar: false, pageZoom: false, }, advancedSettings: true, privacy: { searchPrediction: false, networkPrediction: false, }, downloads: true, a11y: true, extensions: false, languages: true, }; // </if> } else { // All pages are visible when not in chromeos. Since polymer only notifies // after a property is set. // <if expr="chromeos"> pageVisibility = { autofill: true, people: true, onStartup: true, reset: true, safetyCheck: true, appearance: { setTheme: true, homeButton: true, bookmarksBar: true, pageZoom: true, }, advancedSettings: true, privacy: { searchPrediction: true, networkPrediction: true, }, downloads: true, a11y: true, extensions: true, languages: true, }; // </if> } export function
(testVisibility: PageVisibility) { pageVisibility = testVisibility; }
setPageVisibilityForTesting
identifier_name
page_visibility.ts
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; /** * Specifies page visibility based on incognito status and Chrome OS guest mode. */ export type PageVisibility = { a11y?: boolean, advancedSettings?: boolean, appearance?: boolean|AppearancePageVisibility, autofill?: boolean, defaultBrowser?: boolean, downloads?: boolean, extensions?: boolean, languages?: boolean, onStartup?: boolean, people?: boolean, privacy?: boolean|PrivacyPageVisibility, reset?: boolean, safetyCheck?: boolean, }; export type AppearancePageVisibility = { bookmarksBar: boolean, homeButton: boolean, pageZoom: boolean, setTheme: boolean, }; export type PrivacyPageVisibility = { networkPrediction: boolean, searchPrediction: boolean, }; /** * Dictionary defining page visibility. */ export let pageVisibility: PageVisibility; if (loadTimeData.getBoolean('isGuest')) { // "if not chromeos" and "if chromeos" in two completely separate blocks // to work around closure compiler. // <if expr="not (chromeos_ash or chromeos_lacros)"> pageVisibility = { autofill: false, people: false, privacy: false, onStartup: false, reset: false, safetyCheck: false, appearance: false, defaultBrowser: false, advancedSettings: false, extensions: false, languages: false, }; // </if> // <if expr="chromeos_ash or chromeos_lacros"> pageVisibility = { autofill: false, people: false, onStartup: false, reset: false, safetyCheck: false, appearance: { setTheme: false, homeButton: false, bookmarksBar: false, pageZoom: false, }, advancedSettings: true, privacy: { searchPrediction: false, networkPrediction: false, }, downloads: true, a11y: true, extensions: false, languages: true, }; // </if> } else { // All pages are visible when not in chromeos. Since polymer only notifies // after a property is set. // <if expr="chromeos"> pageVisibility = { autofill: true, people: true, onStartup: true, reset: true, safetyCheck: true, appearance: { setTheme: true, homeButton: true, bookmarksBar: true, pageZoom: true, }, advancedSettings: true, privacy: { searchPrediction: true, networkPrediction: true, }, downloads: true, a11y: true, extensions: true, languages: true, }; // </if> } export function setPageVisibilityForTesting(testVisibility: PageVisibility)
{ pageVisibility = testVisibility; }
identifier_body
page_visibility.ts
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; /** * Specifies page visibility based on incognito status and Chrome OS guest mode. */ export type PageVisibility = { a11y?: boolean, advancedSettings?: boolean, appearance?: boolean|AppearancePageVisibility, autofill?: boolean, defaultBrowser?: boolean, downloads?: boolean, extensions?: boolean, languages?: boolean, onStartup?: boolean, people?: boolean, privacy?: boolean|PrivacyPageVisibility, reset?: boolean, safetyCheck?: boolean, }; export type AppearancePageVisibility = { bookmarksBar: boolean, homeButton: boolean, pageZoom: boolean, setTheme: boolean, }; export type PrivacyPageVisibility = { networkPrediction: boolean, searchPrediction: boolean, }; /** * Dictionary defining page visibility. */ export let pageVisibility: PageVisibility; if (loadTimeData.getBoolean('isGuest')) { // "if not chromeos" and "if chromeos" in two completely separate blocks // to work around closure compiler. // <if expr="not (chromeos_ash or chromeos_lacros)"> pageVisibility = { autofill: false, people: false, privacy: false, onStartup: false, reset: false, safetyCheck: false, appearance: false, defaultBrowser: false, advancedSettings: false, extensions: false, languages: false, }; // </if> // <if expr="chromeos_ash or chromeos_lacros"> pageVisibility = { autofill: false, people: false, onStartup: false, reset: false, safetyCheck: false, appearance: { setTheme: false, homeButton: false, bookmarksBar: false, pageZoom: false, }, advancedSettings: true, privacy: { searchPrediction: false, networkPrediction: false, }, downloads: true, a11y: true, extensions: false, languages: true, }; // </if> } else
export function setPageVisibilityForTesting(testVisibility: PageVisibility) { pageVisibility = testVisibility; }
{ // All pages are visible when not in chromeos. Since polymer only notifies // after a property is set. // <if expr="chromeos"> pageVisibility = { autofill: true, people: true, onStartup: true, reset: true, safetyCheck: true, appearance: { setTheme: true, homeButton: true, bookmarksBar: true, pageZoom: true, }, advancedSettings: true, privacy: { searchPrediction: true, networkPrediction: true, }, downloads: true, a11y: true, extensions: true, languages: true, }; // </if> }
conditional_block
classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.js
var classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y = [ [ "swizzleSelf", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#af2e3962f186209cd2f0ff04f2f029a7c", null ], [ "xd", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#a8d5c658a8bea39b4f67274776893005f", null ], [ "xf", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#ae87da1f81a42487596d2dae253090e7b", null ], [ "yd", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#acd1fe537a2fa9132a5e04a4d93bd480d", null ],
[ "yf", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#aee38087663cb9738af856f9168b48920", null ], [ "zd", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#a98665092c02747ae5787ea4a2c368c37", null ], [ "zf", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#a7784563cf410e2f7bff9576e800961b4", null ] ];
random_line_split
models.py
from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from churchill.apps.core.models import BaseModel from churchill.apps.currencies.services import get_default_currency_id class StatsCalculationStrategy(models.TextChoices): LAST_SHOT = "LAST_SHOT", _("From the last shot") WEEKLY = "WEEKLY", _("Weekly") MONTHLY = "MONTHLY", _("Monthly") ALL_TIME = "ALL_TIME", _("For the all time") class Profile(BaseModel): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, related_name="profile", ) image = models.FileField( upload_to=settings.PROFILE_IMAGE_DIRECTORY, null=True, blank=True ) language = models.CharField( max_length=5, blank=True, default=settings.LANGUAGE_CODE, choices=settings.LANGUAGES, ) currency = models.ForeignKey( "currencies.Currency", related_name="profiles", on_delete=models.DO_NOTHING, blank=True, default=get_default_currency_id, ) next_day_offset = models.IntegerField( blank=True, default=settings.NEXT_DAY_OFFSET, help_text=_("Offset in hours for the next day"), ) avg_consumption = models.IntegerField( blank=True, default=settings.AVG_ALCOHOL_CONSUMPTION, help_text=_("Average alcohol consumption in ml per year"), ) avg_price = models.DecimalField( max_digits=5, decimal_places=2, blank=True, default=settings.AVG_ALCOHOL_PRICE, help_text=_("Average alcohol price for 1000 ml"), ) stats_calculation_strategy = models.CharField( max_length=20, choices=StatsCalculationStrategy.choices, default=StatsCalculationStrategy.MONTHLY,
return self.user.email
) verification_token = models.CharField(max_length=16, null=True, blank=True) def __str__(self):
random_line_split
models.py
from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from churchill.apps.core.models import BaseModel from churchill.apps.currencies.services import get_default_currency_id class StatsCalculationStrategy(models.TextChoices): LAST_SHOT = "LAST_SHOT", _("From the last shot") WEEKLY = "WEEKLY", _("Weekly") MONTHLY = "MONTHLY", _("Monthly") ALL_TIME = "ALL_TIME", _("For the all time") class Profile(BaseModel):
user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, related_name="profile", ) image = models.FileField( upload_to=settings.PROFILE_IMAGE_DIRECTORY, null=True, blank=True ) language = models.CharField( max_length=5, blank=True, default=settings.LANGUAGE_CODE, choices=settings.LANGUAGES, ) currency = models.ForeignKey( "currencies.Currency", related_name="profiles", on_delete=models.DO_NOTHING, blank=True, default=get_default_currency_id, ) next_day_offset = models.IntegerField( blank=True, default=settings.NEXT_DAY_OFFSET, help_text=_("Offset in hours for the next day"), ) avg_consumption = models.IntegerField( blank=True, default=settings.AVG_ALCOHOL_CONSUMPTION, help_text=_("Average alcohol consumption in ml per year"), ) avg_price = models.DecimalField( max_digits=5, decimal_places=2, blank=True, default=settings.AVG_ALCOHOL_PRICE, help_text=_("Average alcohol price for 1000 ml"), ) stats_calculation_strategy = models.CharField( max_length=20, choices=StatsCalculationStrategy.choices, default=StatsCalculationStrategy.MONTHLY, ) verification_token = models.CharField(max_length=16, null=True, blank=True) def __str__(self): return self.user.email
identifier_body
models.py
from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from churchill.apps.core.models import BaseModel from churchill.apps.currencies.services import get_default_currency_id class
(models.TextChoices): LAST_SHOT = "LAST_SHOT", _("From the last shot") WEEKLY = "WEEKLY", _("Weekly") MONTHLY = "MONTHLY", _("Monthly") ALL_TIME = "ALL_TIME", _("For the all time") class Profile(BaseModel): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, related_name="profile", ) image = models.FileField( upload_to=settings.PROFILE_IMAGE_DIRECTORY, null=True, blank=True ) language = models.CharField( max_length=5, blank=True, default=settings.LANGUAGE_CODE, choices=settings.LANGUAGES, ) currency = models.ForeignKey( "currencies.Currency", related_name="profiles", on_delete=models.DO_NOTHING, blank=True, default=get_default_currency_id, ) next_day_offset = models.IntegerField( blank=True, default=settings.NEXT_DAY_OFFSET, help_text=_("Offset in hours for the next day"), ) avg_consumption = models.IntegerField( blank=True, default=settings.AVG_ALCOHOL_CONSUMPTION, help_text=_("Average alcohol consumption in ml per year"), ) avg_price = models.DecimalField( max_digits=5, decimal_places=2, blank=True, default=settings.AVG_ALCOHOL_PRICE, help_text=_("Average alcohol price for 1000 ml"), ) stats_calculation_strategy = models.CharField( max_length=20, choices=StatsCalculationStrategy.choices, default=StatsCalculationStrategy.MONTHLY, ) verification_token = models.CharField(max_length=16, null=True, blank=True) def __str__(self): return self.user.email
StatsCalculationStrategy
identifier_name
code_object.rs
use std::os::raw::c_void; use native::*; use native::CodeObject as CodeObjectHandle; use super::{get_info, ErrorStatus}; pub struct CodeObject { pub handle: CodeObjectHandle, } impl CodeObject { pub fn version(&self) -> Result<String, ErrorStatus>
pub fn type_info(&self) -> Result<CodeObjectType, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Type, x)) } pub fn isa(&self) -> Result<ISA, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::ISA, x)) } pub fn machine_model(&self) -> Result<MachineModel, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::MachineModel, x)) } pub fn profile(&self) -> Result<Profile, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Profile, x)) } pub fn default_float_rounding_mode(&self) -> Result<DefaultFloatRoundingMode, ErrorStatus> { get_info(|x| { self.get_info(CodeObjectInfo::DefaultFloatRoundingMode, x) }) } fn get_info(&self, attr: CodeObjectInfo, v: *mut c_void) -> HSAStatus { unsafe { hsa_code_object_get_info(self.handle, attr, v) } } } impl Drop for CodeObject { fn drop(&mut self) { unsafe { hsa_code_object_destroy(self.handle); } } }
{ get_info(|x| self.get_info(CodeObjectInfo::Version, x)).map(|x: [u8; 64]| { let x = x.splitn(2, |c| *c == 0).next().unwrap_or(&[]); String::from_utf8_lossy(x).to_string() }) }
identifier_body
code_object.rs
use std::os::raw::c_void; use native::*; use native::CodeObject as CodeObjectHandle; use super::{get_info, ErrorStatus}; pub struct CodeObject { pub handle: CodeObjectHandle, } impl CodeObject { pub fn version(&self) -> Result<String, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Version, x)).map(|x: [u8; 64]| { let x = x.splitn(2, |c| *c == 0).next().unwrap_or(&[]); String::from_utf8_lossy(x).to_string() }) } pub fn type_info(&self) -> Result<CodeObjectType, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Type, x)) } pub fn isa(&self) -> Result<ISA, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::ISA, x))
pub fn profile(&self) -> Result<Profile, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Profile, x)) } pub fn default_float_rounding_mode(&self) -> Result<DefaultFloatRoundingMode, ErrorStatus> { get_info(|x| { self.get_info(CodeObjectInfo::DefaultFloatRoundingMode, x) }) } fn get_info(&self, attr: CodeObjectInfo, v: *mut c_void) -> HSAStatus { unsafe { hsa_code_object_get_info(self.handle, attr, v) } } } impl Drop for CodeObject { fn drop(&mut self) { unsafe { hsa_code_object_destroy(self.handle); } } }
} pub fn machine_model(&self) -> Result<MachineModel, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::MachineModel, x)) }
random_line_split
code_object.rs
use std::os::raw::c_void; use native::*; use native::CodeObject as CodeObjectHandle; use super::{get_info, ErrorStatus}; pub struct CodeObject { pub handle: CodeObjectHandle, } impl CodeObject { pub fn version(&self) -> Result<String, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Version, x)).map(|x: [u8; 64]| { let x = x.splitn(2, |c| *c == 0).next().unwrap_or(&[]); String::from_utf8_lossy(x).to_string() }) } pub fn type_info(&self) -> Result<CodeObjectType, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Type, x)) } pub fn isa(&self) -> Result<ISA, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::ISA, x)) } pub fn machine_model(&self) -> Result<MachineModel, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::MachineModel, x)) } pub fn profile(&self) -> Result<Profile, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Profile, x)) } pub fn
(&self) -> Result<DefaultFloatRoundingMode, ErrorStatus> { get_info(|x| { self.get_info(CodeObjectInfo::DefaultFloatRoundingMode, x) }) } fn get_info(&self, attr: CodeObjectInfo, v: *mut c_void) -> HSAStatus { unsafe { hsa_code_object_get_info(self.handle, attr, v) } } } impl Drop for CodeObject { fn drop(&mut self) { unsafe { hsa_code_object_destroy(self.handle); } } }
default_float_rounding_mode
identifier_name
IElement.ts
/// <reference path="../IElement.ts" /> module xlib.ui.element.elements.small { import IEvent = elements.IEvent; export interface IElement<T> extends elements.IElement<T> { getTitle(): string; setTitle(value: any): void; getLang(): string; setLang(value: any): void; getXmlLang(): string;
onMouseDown(listener: (event?: IEvent<T>) => void): void; onMouseUp(listener: (event?: IEvent<T>) => void): void; onMouseOver(listener: (event?: IEvent<T>) => void): void; onMouseMove(listener: (event?: IEvent<T>) => void): void; onMouseOut(listener: (event?: IEvent<T>) => void): void; onKeyPress(listener: (event?: IEvent<T>) => void): void; onKeyDown(listener: (event?: IEvent<T>) => void): void; onKeyUp(listener: (event?: IEvent<T>) => void): void; } }
setXmlLang(value: any): void; getDir(): string; setDir(value: any): void; onClick(listener: (event?: IEvent<T>) => void): void; onDblClick(listener: (event?: IEvent<T>) => void): void;
random_line_split
base.py
import inspect import os import sys from datetime import timedelta from io import StringIO from unittest.mock import Mock from urllib.error import HTTPError import django import django.db import django.test.runner import django.test.testcases import django.test.utils from django.test import TestCase from aid.test.data import gen_member, gen_api_ladder from aid.test.db import Db from common.utils import to_unix, utcnow, classinstancemethod from lib import sc2 from main.battle_net import LeagueResponse, ApiLeague, SeasonResponse, ApiSeason, LadderResponse, BnetClient from main.models import Region, Enums, Mode, Version, League # warnings.filterwarnings('ignore') class DjangoTestCase(TestCase): # This is really ugly hack of django test framework. This was made a long time ago maybe possible to make it # better now, since djanog test framwork have been changed a lot. The c++ code needs to access the database so # the django postgresql test rollback scheme does not really work. Since using postgresql like this makes the # tests so slow sqlite is used for tests that doew not require postgresql. This makes it impossible to run # them in the same process. # # Sometimes it is useful to debug the db. Set the KEEP_DATA environment variable to prevent deletion of the # database. maxDiff = 1e4 def __str__(self): """ Return a string that can be used as a command line argument to nose. """ return "%s:%s.%s" % (inspect.getfile(self.__class__), self.__class__.__name__, self._testMethodName) @classmethod def _enter_atomics(cls): # Prevent rollbacks. pass @classmethod def _rollback_atomics(cls, atomics): # Prevent rollbacks. pass def _fixture_teardown(self): # Prevent clearing of test data. pass @classmethod def setUpClass(self): super().setUpClass() self.runner = django.test.runner.DiscoverRunner(interactive=False) django.test.utils.setup_test_environment() self.old_config = self.runner.setup_databases() self.db = Db() @classmethod def tearDownClass(self): if 'KEEP_DATA' in os.environ: print("\nkeeping test database: %r." % self.db.db_name, file=sys.stderr) else: self.db.delete_all() self.runner.teardown_databases(self.old_config) django.test.utils.teardown_test_environment() super().tearDownClass() def tearDown(self): if hasattr(self, 'cpp') and self.cpp is not None: self.cpp.release() self.cpp = None super().tearDown() def load(self): self.cpp = sc2.RankingData(self.db.db_name, Enums.INFO) self.cpp.load(self.db.ranking.id) def process_ladder(self, load=False, save=False, region=Region.EU, fetch_time=None, mode=Mode.TEAM_1V1, version=Version.HOTS, league=League.GOLD, season=None, tier=0, members=None, **kwargs): """ Update a ranking building single member with kwargs or use members if set. """ season = season or self.db.season fetch_time = fetch_time or utcnow() members = members or [gen_member(**kwargs)] if not getattr(self, 'cpp', None): self.cpp = sc2.RankingData(self.db.db_name, Enums.INFO) if load: self.load() self.cpp.update_with_ladder(0, # bid 0, # source_id region, mode, league, tier, version, season.id, to_unix(fetch_time), fetch_time.date().isoformat(), Mode.team_size(mode), members) if save: self.save_to_ranking() def save_to_ranking(self): self.cpp.save_data(self.db.ranking.id, self.db.ranking.season_id, to_unix(utcnow())) @classinstancemethod def date(self, **kwargs): return self.today + timedelta(**kwargs) @classinstancemethod def datetime(self, **kwargs): return self.now + timedelta(**kwargs) @classinstancemethod def unix_time(self, **kwargs): return to_unix(self.now + timedelta(**kwargs)) def assert_team_ranks(self, ranking_id, *ranks, skip_len=False, sort=True): """ Get all team ranks using the current ranking id and assert that all ranks corresponds to team ranks in db. All keys in ranks will be verified against team ranks values. """ team_ranks = sc2.get_team_ranks(self.db.db_name, ranking_id, sort) all_keys = {key for rank in ranks for key in rank} try: if not skip_len: self.assertEqual(len(team_ranks), len(ranks)) for i, (team_rank, r) in enumerate(zip(team_ranks, ranks), start=1): for key, value in r.items(): self.assertEqual(value, team_rank[key], msg="%s wrong @ rank %d, expected %r, was %r" % (key, i, r, {key: team_rank.get(key, None) for key in r.keys()})) except AssertionError: print("Expected:\n%s" % "\n".join([repr(tr) for tr in ranks])) print("Actual:\n%s" % "\n".join([repr({k: v for k, v in tr.items() if k in all_keys}) for tr in team_ranks])) raise class MockBnetTestMixin(object): """ Class to help with common mockings. """ def setUp(self): super().setUp() self.bnet = BnetClient() def mock_raw_get(self, status=200, content=""): self.bnet.raw_get = Mock(side_effect=HTTPError('', status, '', '', StringIO(content))) def mock_current_season(self, status=200, season_id=None, start_time=None, fetch_time=None):
def mock_fetch_ladder(self, status=200, fetch_time=None, members=None, **kwargs): self.bnet.fetch_ladder = \ Mock(return_value=LadderResponse(status, gen_api_ladder(members, **kwargs), fetch_time or utcnow(), 0)) def mock_fetch_league(self, status=200, fetch_time=None, season_id=None, t0_bids=None, t1_bids=None, t2_bids=None): season_id = season_id or self.db.season.id self.bnet.fetch_league = \ Mock(return_value=LeagueResponse(status, ApiLeague({'tier': [ {'id': 0, 'division': [{'ladder_id': lid} for lid in t0_bids or []]}, {'id': 1, 'division': [{'ladder_id': lid} for lid in t1_bids or []]}, {'id': 2, 'division': [{'ladder_id': lid} for lid in t2_bids or []]}, ]}, url="http://fake-url", bid=season_id * 100000), fetch_time or utcnow(), 0))
self.bnet.fetch_current_season = \ Mock(return_value=SeasonResponse(status, ApiSeason({'seasonId': season_id or self.db.season.id, 'startDate': to_unix(start_time or utcnow())}, 'http://fake-url'), fetch_time or utcnow(), 0))
identifier_body
base.py
import inspect import os import sys from datetime import timedelta from io import StringIO from unittest.mock import Mock from urllib.error import HTTPError import django import django.db import django.test.runner import django.test.testcases import django.test.utils from django.test import TestCase from aid.test.data import gen_member, gen_api_ladder from aid.test.db import Db from common.utils import to_unix, utcnow, classinstancemethod from lib import sc2 from main.battle_net import LeagueResponse, ApiLeague, SeasonResponse, ApiSeason, LadderResponse, BnetClient from main.models import Region, Enums, Mode, Version, League # warnings.filterwarnings('ignore') class DjangoTestCase(TestCase): # This is really ugly hack of django test framework. This was made a long time ago maybe possible to make it # better now, since djanog test framwork have been changed a lot. The c++ code needs to access the database so # the django postgresql test rollback scheme does not really work. Since using postgresql like this makes the # tests so slow sqlite is used for tests that doew not require postgresql. This makes it impossible to run # them in the same process. # # Sometimes it is useful to debug the db. Set the KEEP_DATA environment variable to prevent deletion of the # database. maxDiff = 1e4 def __str__(self): """ Return a string that can be used as a command line argument to nose. """ return "%s:%s.%s" % (inspect.getfile(self.__class__), self.__class__.__name__, self._testMethodName) @classmethod def _enter_atomics(cls): # Prevent rollbacks. pass @classmethod def _rollback_atomics(cls, atomics): # Prevent rollbacks. pass def _fixture_teardown(self): # Prevent clearing of test data. pass @classmethod def setUpClass(self): super().setUpClass() self.runner = django.test.runner.DiscoverRunner(interactive=False) django.test.utils.setup_test_environment() self.old_config = self.runner.setup_databases() self.db = Db() @classmethod def tearDownClass(self): if 'KEEP_DATA' in os.environ: print("\nkeeping test database: %r." % self.db.db_name, file=sys.stderr) else: self.db.delete_all() self.runner.teardown_databases(self.old_config) django.test.utils.teardown_test_environment() super().tearDownClass() def tearDown(self): if hasattr(self, 'cpp') and self.cpp is not None: self.cpp.release() self.cpp = None super().tearDown() def load(self): self.cpp = sc2.RankingData(self.db.db_name, Enums.INFO) self.cpp.load(self.db.ranking.id) def process_ladder(self, load=False, save=False, region=Region.EU, fetch_time=None, mode=Mode.TEAM_1V1, version=Version.HOTS, league=League.GOLD, season=None, tier=0, members=None, **kwargs): """ Update a ranking building single member with kwargs or use members if set. """ season = season or self.db.season fetch_time = fetch_time or utcnow() members = members or [gen_member(**kwargs)] if not getattr(self, 'cpp', None): self.cpp = sc2.RankingData(self.db.db_name, Enums.INFO) if load:
self.cpp.update_with_ladder(0, # bid 0, # source_id region, mode, league, tier, version, season.id, to_unix(fetch_time), fetch_time.date().isoformat(), Mode.team_size(mode), members) if save: self.save_to_ranking() def save_to_ranking(self): self.cpp.save_data(self.db.ranking.id, self.db.ranking.season_id, to_unix(utcnow())) @classinstancemethod def date(self, **kwargs): return self.today + timedelta(**kwargs) @classinstancemethod def datetime(self, **kwargs): return self.now + timedelta(**kwargs) @classinstancemethod def unix_time(self, **kwargs): return to_unix(self.now + timedelta(**kwargs)) def assert_team_ranks(self, ranking_id, *ranks, skip_len=False, sort=True): """ Get all team ranks using the current ranking id and assert that all ranks corresponds to team ranks in db. All keys in ranks will be verified against team ranks values. """ team_ranks = sc2.get_team_ranks(self.db.db_name, ranking_id, sort) all_keys = {key for rank in ranks for key in rank} try: if not skip_len: self.assertEqual(len(team_ranks), len(ranks)) for i, (team_rank, r) in enumerate(zip(team_ranks, ranks), start=1): for key, value in r.items(): self.assertEqual(value, team_rank[key], msg="%s wrong @ rank %d, expected %r, was %r" % (key, i, r, {key: team_rank.get(key, None) for key in r.keys()})) except AssertionError: print("Expected:\n%s" % "\n".join([repr(tr) for tr in ranks])) print("Actual:\n%s" % "\n".join([repr({k: v for k, v in tr.items() if k in all_keys}) for tr in team_ranks])) raise class MockBnetTestMixin(object): """ Class to help with common mockings. """ def setUp(self): super().setUp() self.bnet = BnetClient() def mock_raw_get(self, status=200, content=""): self.bnet.raw_get = Mock(side_effect=HTTPError('', status, '', '', StringIO(content))) def mock_current_season(self, status=200, season_id=None, start_time=None, fetch_time=None): self.bnet.fetch_current_season = \ Mock(return_value=SeasonResponse(status, ApiSeason({'seasonId': season_id or self.db.season.id, 'startDate': to_unix(start_time or utcnow())}, 'http://fake-url'), fetch_time or utcnow(), 0)) def mock_fetch_ladder(self, status=200, fetch_time=None, members=None, **kwargs): self.bnet.fetch_ladder = \ Mock(return_value=LadderResponse(status, gen_api_ladder(members, **kwargs), fetch_time or utcnow(), 0)) def mock_fetch_league(self, status=200, fetch_time=None, season_id=None, t0_bids=None, t1_bids=None, t2_bids=None): season_id = season_id or self.db.season.id self.bnet.fetch_league = \ Mock(return_value=LeagueResponse(status, ApiLeague({'tier': [ {'id': 0, 'division': [{'ladder_id': lid} for lid in t0_bids or []]}, {'id': 1, 'division': [{'ladder_id': lid} for lid in t1_bids or []]}, {'id': 2, 'division': [{'ladder_id': lid} for lid in t2_bids or []]}, ]}, url="http://fake-url", bid=season_id * 100000), fetch_time or utcnow(), 0))
self.load()
conditional_block
base.py
import inspect import os import sys from datetime import timedelta from io import StringIO from unittest.mock import Mock from urllib.error import HTTPError import django import django.db import django.test.runner import django.test.testcases import django.test.utils from django.test import TestCase from aid.test.data import gen_member, gen_api_ladder from aid.test.db import Db from common.utils import to_unix, utcnow, classinstancemethod from lib import sc2 from main.battle_net import LeagueResponse, ApiLeague, SeasonResponse, ApiSeason, LadderResponse, BnetClient from main.models import Region, Enums, Mode, Version, League # warnings.filterwarnings('ignore') class DjangoTestCase(TestCase): # This is really ugly hack of django test framework. This was made a long time ago maybe possible to make it # better now, since djanog test framwork have been changed a lot. The c++ code needs to access the database so # the django postgresql test rollback scheme does not really work. Since using postgresql like this makes the # tests so slow sqlite is used for tests that doew not require postgresql. This makes it impossible to run # them in the same process. # # Sometimes it is useful to debug the db. Set the KEEP_DATA environment variable to prevent deletion of the # database. maxDiff = 1e4 def __str__(self): """ Return a string that can be used as a command line argument to nose. """ return "%s:%s.%s" % (inspect.getfile(self.__class__), self.__class__.__name__, self._testMethodName) @classmethod def _enter_atomics(cls): # Prevent rollbacks. pass @classmethod def _rollback_atomics(cls, atomics): # Prevent rollbacks. pass def _fixture_teardown(self): # Prevent clearing of test data. pass @classmethod def setUpClass(self): super().setUpClass() self.runner = django.test.runner.DiscoverRunner(interactive=False) django.test.utils.setup_test_environment() self.old_config = self.runner.setup_databases() self.db = Db() @classmethod def tearDownClass(self): if 'KEEP_DATA' in os.environ: print("\nkeeping test database: %r." % self.db.db_name, file=sys.stderr) else: self.db.delete_all() self.runner.teardown_databases(self.old_config) django.test.utils.teardown_test_environment() super().tearDownClass() def tearDown(self): if hasattr(self, 'cpp') and self.cpp is not None: self.cpp.release() self.cpp = None super().tearDown() def load(self): self.cpp = sc2.RankingData(self.db.db_name, Enums.INFO) self.cpp.load(self.db.ranking.id) def process_ladder(self, load=False, save=False, region=Region.EU, fetch_time=None, mode=Mode.TEAM_1V1, version=Version.HOTS, league=League.GOLD, season=None, tier=0, members=None, **kwargs): """ Update a ranking building single member with kwargs or use members if set. """ season = season or self.db.season fetch_time = fetch_time or utcnow() members = members or [gen_member(**kwargs)] if not getattr(self, 'cpp', None): self.cpp = sc2.RankingData(self.db.db_name, Enums.INFO) if load: self.load() self.cpp.update_with_ladder(0, # bid 0, # source_id region, mode, league, tier, version, season.id, to_unix(fetch_time), fetch_time.date().isoformat(), Mode.team_size(mode), members) if save: self.save_to_ranking() def save_to_ranking(self): self.cpp.save_data(self.db.ranking.id, self.db.ranking.season_id, to_unix(utcnow())) @classinstancemethod def date(self, **kwargs): return self.today + timedelta(**kwargs) @classinstancemethod def
(self, **kwargs): return self.now + timedelta(**kwargs) @classinstancemethod def unix_time(self, **kwargs): return to_unix(self.now + timedelta(**kwargs)) def assert_team_ranks(self, ranking_id, *ranks, skip_len=False, sort=True): """ Get all team ranks using the current ranking id and assert that all ranks corresponds to team ranks in db. All keys in ranks will be verified against team ranks values. """ team_ranks = sc2.get_team_ranks(self.db.db_name, ranking_id, sort) all_keys = {key for rank in ranks for key in rank} try: if not skip_len: self.assertEqual(len(team_ranks), len(ranks)) for i, (team_rank, r) in enumerate(zip(team_ranks, ranks), start=1): for key, value in r.items(): self.assertEqual(value, team_rank[key], msg="%s wrong @ rank %d, expected %r, was %r" % (key, i, r, {key: team_rank.get(key, None) for key in r.keys()})) except AssertionError: print("Expected:\n%s" % "\n".join([repr(tr) for tr in ranks])) print("Actual:\n%s" % "\n".join([repr({k: v for k, v in tr.items() if k in all_keys}) for tr in team_ranks])) raise class MockBnetTestMixin(object): """ Class to help with common mockings. """ def setUp(self): super().setUp() self.bnet = BnetClient() def mock_raw_get(self, status=200, content=""): self.bnet.raw_get = Mock(side_effect=HTTPError('', status, '', '', StringIO(content))) def mock_current_season(self, status=200, season_id=None, start_time=None, fetch_time=None): self.bnet.fetch_current_season = \ Mock(return_value=SeasonResponse(status, ApiSeason({'seasonId': season_id or self.db.season.id, 'startDate': to_unix(start_time or utcnow())}, 'http://fake-url'), fetch_time or utcnow(), 0)) def mock_fetch_ladder(self, status=200, fetch_time=None, members=None, **kwargs): self.bnet.fetch_ladder = \ Mock(return_value=LadderResponse(status, gen_api_ladder(members, **kwargs), fetch_time or utcnow(), 0)) def mock_fetch_league(self, status=200, fetch_time=None, season_id=None, t0_bids=None, t1_bids=None, t2_bids=None): season_id = season_id or self.db.season.id self.bnet.fetch_league = \ Mock(return_value=LeagueResponse(status, ApiLeague({'tier': [ {'id': 0, 'division': [{'ladder_id': lid} for lid in t0_bids or []]}, {'id': 1, 'division': [{'ladder_id': lid} for lid in t1_bids or []]}, {'id': 2, 'division': [{'ladder_id': lid} for lid in t2_bids or []]}, ]}, url="http://fake-url", bid=season_id * 100000), fetch_time or utcnow(), 0))
datetime
identifier_name
base.py
import inspect import os import sys from datetime import timedelta from io import StringIO from unittest.mock import Mock from urllib.error import HTTPError import django import django.db import django.test.runner import django.test.testcases import django.test.utils from django.test import TestCase from aid.test.data import gen_member, gen_api_ladder from aid.test.db import Db from common.utils import to_unix, utcnow, classinstancemethod from lib import sc2 from main.battle_net import LeagueResponse, ApiLeague, SeasonResponse, ApiSeason, LadderResponse, BnetClient from main.models import Region, Enums, Mode, Version, League # warnings.filterwarnings('ignore') class DjangoTestCase(TestCase): # This is really ugly hack of django test framework. This was made a long time ago maybe possible to make it # better now, since djanog test framwork have been changed a lot. The c++ code needs to access the database so # the django postgresql test rollback scheme does not really work. Since using postgresql like this makes the # tests so slow sqlite is used for tests that doew not require postgresql. This makes it impossible to run # them in the same process. # # Sometimes it is useful to debug the db. Set the KEEP_DATA environment variable to prevent deletion of the # database. maxDiff = 1e4 def __str__(self): """ Return a string that can be used as a command line argument to nose. """ return "%s:%s.%s" % (inspect.getfile(self.__class__), self.__class__.__name__, self._testMethodName) @classmethod def _enter_atomics(cls): # Prevent rollbacks. pass @classmethod def _rollback_atomics(cls, atomics): # Prevent rollbacks. pass def _fixture_teardown(self): # Prevent clearing of test data. pass @classmethod def setUpClass(self): super().setUpClass() self.runner = django.test.runner.DiscoverRunner(interactive=False) django.test.utils.setup_test_environment() self.old_config = self.runner.setup_databases() self.db = Db() @classmethod def tearDownClass(self): if 'KEEP_DATA' in os.environ: print("\nkeeping test database: %r." % self.db.db_name, file=sys.stderr) else: self.db.delete_all() self.runner.teardown_databases(self.old_config) django.test.utils.teardown_test_environment() super().tearDownClass() def tearDown(self): if hasattr(self, 'cpp') and self.cpp is not None: self.cpp.release() self.cpp = None super().tearDown() def load(self): self.cpp = sc2.RankingData(self.db.db_name, Enums.INFO) self.cpp.load(self.db.ranking.id) def process_ladder(self, load=False, save=False, region=Region.EU, fetch_time=None, mode=Mode.TEAM_1V1, version=Version.HOTS, league=League.GOLD, season=None, tier=0, members=None, **kwargs): """ Update a ranking building single member with kwargs or use members if set. """ season = season or self.db.season fetch_time = fetch_time or utcnow() members = members or [gen_member(**kwargs)] if not getattr(self, 'cpp', None): self.cpp = sc2.RankingData(self.db.db_name, Enums.INFO) if load: self.load() self.cpp.update_with_ladder(0, # bid 0, # source_id region, mode, league, tier, version, season.id, to_unix(fetch_time), fetch_time.date().isoformat(), Mode.team_size(mode), members) if save: self.save_to_ranking() def save_to_ranking(self): self.cpp.save_data(self.db.ranking.id, self.db.ranking.season_id, to_unix(utcnow())) @classinstancemethod def date(self, **kwargs): return self.today + timedelta(**kwargs) @classinstancemethod def datetime(self, **kwargs): return self.now + timedelta(**kwargs) @classinstancemethod def unix_time(self, **kwargs): return to_unix(self.now + timedelta(**kwargs)) def assert_team_ranks(self, ranking_id, *ranks, skip_len=False, sort=True): """ Get all team ranks using the current ranking id and assert that all ranks corresponds to team ranks in db. All keys in ranks will be verified against team ranks values. """ team_ranks = sc2.get_team_ranks(self.db.db_name, ranking_id, sort) all_keys = {key for rank in ranks for key in rank} try: if not skip_len: self.assertEqual(len(team_ranks), len(ranks)) for i, (team_rank, r) in enumerate(zip(team_ranks, ranks), start=1): for key, value in r.items(): self.assertEqual(value, team_rank[key], msg="%s wrong @ rank %d, expected %r, was %r" % (key, i, r, {key: team_rank.get(key, None) for key in r.keys()})) except AssertionError: print("Expected:\n%s" % "\n".join([repr(tr) for tr in ranks])) print("Actual:\n%s" % "\n".join([repr({k: v for k, v in tr.items() if k in all_keys})
class MockBnetTestMixin(object): """ Class to help with common mockings. """ def setUp(self): super().setUp() self.bnet = BnetClient() def mock_raw_get(self, status=200, content=""): self.bnet.raw_get = Mock(side_effect=HTTPError('', status, '', '', StringIO(content))) def mock_current_season(self, status=200, season_id=None, start_time=None, fetch_time=None): self.bnet.fetch_current_season = \ Mock(return_value=SeasonResponse(status, ApiSeason({'seasonId': season_id or self.db.season.id, 'startDate': to_unix(start_time or utcnow())}, 'http://fake-url'), fetch_time or utcnow(), 0)) def mock_fetch_ladder(self, status=200, fetch_time=None, members=None, **kwargs): self.bnet.fetch_ladder = \ Mock(return_value=LadderResponse(status, gen_api_ladder(members, **kwargs), fetch_time or utcnow(), 0)) def mock_fetch_league(self, status=200, fetch_time=None, season_id=None, t0_bids=None, t1_bids=None, t2_bids=None): season_id = season_id or self.db.season.id self.bnet.fetch_league = \ Mock(return_value=LeagueResponse(status, ApiLeague({'tier': [ {'id': 0, 'division': [{'ladder_id': lid} for lid in t0_bids or []]}, {'id': 1, 'division': [{'ladder_id': lid} for lid in t1_bids or []]}, {'id': 2, 'division': [{'ladder_id': lid} for lid in t2_bids or []]}, ]}, url="http://fake-url", bid=season_id * 100000), fetch_time or utcnow(), 0))
for tr in team_ranks])) raise
random_line_split
test_cron.py
import datetime import os from django.conf import settings from olympia.amo.tests import TestCase from olympia.addons.models import Addon from olympia.devhub.cron import update_blog_posts from olympia.devhub.tasks import convert_purified from olympia.devhub.models import BlogPost class TestRSS(TestCase): def test_rss_cron(self): url = os.path.join( settings.ROOT, 'src', 'olympia', 'devhub', 'tests', 'rss_feeds', 'blog.xml') settings.DEVELOPER_BLOG_URL = url update_blog_posts() assert BlogPost.objects.count() == 5 bp = BlogPost.objects.all()[0] url = ("http://blog.mozilla.com/addons/2011/06/10/" "update-in-time-for-thunderbird-5/") assert bp.title == 'Test!' assert bp.date_posted == datetime.date(2011, 6, 10) assert bp.permalink == url class TestPurify(TestCase): fixtures = ['base/addon_3615'] def setUp(self): super(TestPurify, self).setUp() self.addon = Addon.objects.get(pk=3615) def test_no_html(self): self.addon.the_reason = 'foo' self.addon.save() last = Addon.objects.get(pk=3615).modified convert_purified([self.addon.pk]) addon = Addon.objects.get(pk=3615) assert addon.modified == last def test_has_html(self):
self.addon.the_reason = 'foo <script>foo</script>' self.addon.save() convert_purified([self.addon.pk]) addon = Addon.objects.get(pk=3615) assert addon.the_reason.localized_string_clean
identifier_body
test_cron.py
import datetime import os from django.conf import settings from olympia.amo.tests import TestCase from olympia.addons.models import Addon from olympia.devhub.cron import update_blog_posts from olympia.devhub.tasks import convert_purified from olympia.devhub.models import BlogPost class TestRSS(TestCase): def test_rss_cron(self): url = os.path.join( settings.ROOT, 'src', 'olympia', 'devhub', 'tests', 'rss_feeds', 'blog.xml') settings.DEVELOPER_BLOG_URL = url update_blog_posts() assert BlogPost.objects.count() == 5 bp = BlogPost.objects.all()[0] url = ("http://blog.mozilla.com/addons/2011/06/10/" "update-in-time-for-thunderbird-5/") assert bp.title == 'Test!' assert bp.date_posted == datetime.date(2011, 6, 10) assert bp.permalink == url class TestPurify(TestCase): fixtures = ['base/addon_3615'] def
(self): super(TestPurify, self).setUp() self.addon = Addon.objects.get(pk=3615) def test_no_html(self): self.addon.the_reason = 'foo' self.addon.save() last = Addon.objects.get(pk=3615).modified convert_purified([self.addon.pk]) addon = Addon.objects.get(pk=3615) assert addon.modified == last def test_has_html(self): self.addon.the_reason = 'foo <script>foo</script>' self.addon.save() convert_purified([self.addon.pk]) addon = Addon.objects.get(pk=3615) assert addon.the_reason.localized_string_clean
setUp
identifier_name
test_cron.py
import datetime import os from django.conf import settings from olympia.amo.tests import TestCase from olympia.addons.models import Addon from olympia.devhub.cron import update_blog_posts from olympia.devhub.tasks import convert_purified from olympia.devhub.models import BlogPost class TestRSS(TestCase): def test_rss_cron(self): url = os.path.join( settings.ROOT, 'src', 'olympia', 'devhub', 'tests', 'rss_feeds', 'blog.xml') settings.DEVELOPER_BLOG_URL = url update_blog_posts() assert BlogPost.objects.count() == 5 bp = BlogPost.objects.all()[0] url = ("http://blog.mozilla.com/addons/2011/06/10/" "update-in-time-for-thunderbird-5/")
class TestPurify(TestCase): fixtures = ['base/addon_3615'] def setUp(self): super(TestPurify, self).setUp() self.addon = Addon.objects.get(pk=3615) def test_no_html(self): self.addon.the_reason = 'foo' self.addon.save() last = Addon.objects.get(pk=3615).modified convert_purified([self.addon.pk]) addon = Addon.objects.get(pk=3615) assert addon.modified == last def test_has_html(self): self.addon.the_reason = 'foo <script>foo</script>' self.addon.save() convert_purified([self.addon.pk]) addon = Addon.objects.get(pk=3615) assert addon.the_reason.localized_string_clean
assert bp.title == 'Test!' assert bp.date_posted == datetime.date(2011, 6, 10) assert bp.permalink == url
random_line_split
mod.rs
use piston_window; use piston_window::{Context, G2d, Glyphs, RenderArgs, Transformed}; use piston_window::types::Scalar; use rusttype::{Rect, Scale, VMetrics}; use {GameState, InnerState, Progress}; mod text; /// Draws the game state. pub fn
(state: &GameState, render_args: RenderArgs, context: Context, graphics: &mut G2d, glyphs: &mut Glyphs) { let black = [0.0, 0.0, 0.0, 1.0]; let white = [1.0, 1.0, 1.0, 1.0]; piston_window::clear(black, graphics); let border = 32.0; // thickness of border, in pixels let (title, shake) = match state.state { InnerState::Falling(progress) => { ((render_args.height as Scalar - border) * progress * progress, 0.0) } InnerState::Settling(progress) => { (render_args.height as Scalar - border, border * (1.0 - progress) * Progress::sin(progress * 64.0)) } InnerState::Done => (render_args.height as Scalar - border, 0.0), }; { let points = 16; let pixels = text::points_to_pixels(points); let VMetrics { ascent, descent, .. } = glyphs.font .v_metrics(Scale::uniform(pixels)); let fps_text = format!("{} FPS", state.fps); let mut draw = |text, x: &Fn(Rect<f32>) -> Scalar, y| { let bounding_box = text::bounding_box(&glyphs.font, pixels, text) .unwrap(); let transform = context.transform.trans(x(bounding_box), y); piston_window::text(white, points, text, glyphs, transform, graphics); }; draw("Games, Inc.", &|bounding_box| border - bounding_box.min.x as Scalar, border + ascent as Scalar + shake); draw("This is some text.", &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar }, border + ascent as Scalar + shake); draw("Copyright 1942", &|bounding_box| border - bounding_box.min.x as Scalar, render_args.height as Scalar - border + descent as Scalar + shake); draw(&fps_text, &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar }, render_args.height as Scalar - border + descent as Scalar + shake); } let text = "COUNTDOWN"; let points = 128; let pixels = text::points_to_pixels(points); let bounding_box = text::bounding_box(&glyphs.font, pixels, text).unwrap(); let transform = context.transform .trans(render_args.width as Scalar / 2.0 - (bounding_box.min.x + bounding_box.width() / 2.0) as Scalar, title + shake + glyphs.font.v_metrics(Scale::uniform(pixels)).descent as Scalar); piston_window::text(white, points, text, glyphs, transform, graphics); }
draw
identifier_name
mod.rs
use piston_window; use piston_window::{Context, G2d, Glyphs, RenderArgs, Transformed}; use piston_window::types::Scalar; use rusttype::{Rect, Scale, VMetrics}; use {GameState, InnerState, Progress}; mod text; /// Draws the game state. pub fn draw(state: &GameState, render_args: RenderArgs, context: Context, graphics: &mut G2d, glyphs: &mut Glyphs) { let black = [0.0, 0.0, 0.0, 1.0]; let white = [1.0, 1.0, 1.0, 1.0]; piston_window::clear(black, graphics); let border = 32.0; // thickness of border, in pixels let (title, shake) = match state.state { InnerState::Falling(progress) => { ((render_args.height as Scalar - border) * progress * progress, 0.0) } InnerState::Settling(progress) => { (render_args.height as Scalar - border, border * (1.0 - progress) * Progress::sin(progress * 64.0)) } InnerState::Done => (render_args.height as Scalar - border, 0.0), }; { let points = 16; let pixels = text::points_to_pixels(points); let VMetrics { ascent, descent, .. } = glyphs.font .v_metrics(Scale::uniform(pixels)); let fps_text = format!("{} FPS", state.fps); let mut draw = |text, x: &Fn(Rect<f32>) -> Scalar, y| { let bounding_box = text::bounding_box(&glyphs.font, pixels, text) .unwrap(); let transform = context.transform.trans(x(bounding_box), y); piston_window::text(white, points, text, glyphs, transform, graphics); }; draw("Games, Inc.", &|bounding_box| border - bounding_box.min.x as Scalar, border + ascent as Scalar + shake);
}, border + ascent as Scalar + shake); draw("Copyright 1942", &|bounding_box| border - bounding_box.min.x as Scalar, render_args.height as Scalar - border + descent as Scalar + shake); draw(&fps_text, &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar }, render_args.height as Scalar - border + descent as Scalar + shake); } let text = "COUNTDOWN"; let points = 128; let pixels = text::points_to_pixels(points); let bounding_box = text::bounding_box(&glyphs.font, pixels, text).unwrap(); let transform = context.transform .trans(render_args.width as Scalar / 2.0 - (bounding_box.min.x + bounding_box.width() / 2.0) as Scalar, title + shake + glyphs.font.v_metrics(Scale::uniform(pixels)).descent as Scalar); piston_window::text(white, points, text, glyphs, transform, graphics); }
draw("This is some text.", &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar
random_line_split
mod.rs
use piston_window; use piston_window::{Context, G2d, Glyphs, RenderArgs, Transformed}; use piston_window::types::Scalar; use rusttype::{Rect, Scale, VMetrics}; use {GameState, InnerState, Progress}; mod text; /// Draws the game state. pub fn draw(state: &GameState, render_args: RenderArgs, context: Context, graphics: &mut G2d, glyphs: &mut Glyphs)
{ let black = [0.0, 0.0, 0.0, 1.0]; let white = [1.0, 1.0, 1.0, 1.0]; piston_window::clear(black, graphics); let border = 32.0; // thickness of border, in pixels let (title, shake) = match state.state { InnerState::Falling(progress) => { ((render_args.height as Scalar - border) * progress * progress, 0.0) } InnerState::Settling(progress) => { (render_args.height as Scalar - border, border * (1.0 - progress) * Progress::sin(progress * 64.0)) } InnerState::Done => (render_args.height as Scalar - border, 0.0), }; { let points = 16; let pixels = text::points_to_pixels(points); let VMetrics { ascent, descent, .. } = glyphs.font .v_metrics(Scale::uniform(pixels)); let fps_text = format!("{} FPS", state.fps); let mut draw = |text, x: &Fn(Rect<f32>) -> Scalar, y| { let bounding_box = text::bounding_box(&glyphs.font, pixels, text) .unwrap(); let transform = context.transform.trans(x(bounding_box), y); piston_window::text(white, points, text, glyphs, transform, graphics); }; draw("Games, Inc.", &|bounding_box| border - bounding_box.min.x as Scalar, border + ascent as Scalar + shake); draw("This is some text.", &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar }, border + ascent as Scalar + shake); draw("Copyright 1942", &|bounding_box| border - bounding_box.min.x as Scalar, render_args.height as Scalar - border + descent as Scalar + shake); draw(&fps_text, &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar }, render_args.height as Scalar - border + descent as Scalar + shake); } let text = "COUNTDOWN"; let points = 128; let pixels = text::points_to_pixels(points); let bounding_box = text::bounding_box(&glyphs.font, pixels, text).unwrap(); let transform = context.transform .trans(render_args.width as Scalar / 2.0 - (bounding_box.min.x + bounding_box.width() / 2.0) as Scalar, title + shake + glyphs.font.v_metrics(Scale::uniform(pixels)).descent as Scalar); piston_window::text(white, points, text, glyphs, transform, graphics); }
identifier_body
generic.py
# (void)walker CPU architecture support # Copyright (C) 2013 David Holm <dholmster@gmail.com> # 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. from ...framework.platform import Architecture from ...framework.platform import Cpu from ...framework.platform import Register from ...framework.platform import register_cpu @register_cpu class GenericCpu(Cpu):
def __init__(self, cpu_factory, registers): for group, register_list in registers.iteritems(): registers[group] = [Register(x) for x in register_list] super(GenericCpu, self).__init__(cpu_factory, registers) @classmethod def architecture(cls): return Architecture.Generic def stack_pointer(self): return self.register('sp') def program_counter(self): return self.register('pc')
identifier_body
generic.py
# (void)walker CPU architecture support # Copyright (C) 2013 David Holm <dholmster@gmail.com> # 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. from ...framework.platform import Architecture from ...framework.platform import Cpu from ...framework.platform import Register from ...framework.platform import register_cpu @register_cpu class GenericCpu(Cpu): def __init__(self, cpu_factory, registers): for group, register_list in registers.iteritems():
super(GenericCpu, self).__init__(cpu_factory, registers) @classmethod def architecture(cls): return Architecture.Generic def stack_pointer(self): return self.register('sp') def program_counter(self): return self.register('pc')
registers[group] = [Register(x) for x in register_list]
conditional_block
generic.py
# (void)walker CPU architecture support
# 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. from ...framework.platform import Architecture from ...framework.platform import Cpu from ...framework.platform import Register from ...framework.platform import register_cpu @register_cpu class GenericCpu(Cpu): def __init__(self, cpu_factory, registers): for group, register_list in registers.iteritems(): registers[group] = [Register(x) for x in register_list] super(GenericCpu, self).__init__(cpu_factory, registers) @classmethod def architecture(cls): return Architecture.Generic def stack_pointer(self): return self.register('sp') def program_counter(self): return self.register('pc')
# Copyright (C) 2013 David Holm <dholmster@gmail.com>
random_line_split
generic.py
# (void)walker CPU architecture support # Copyright (C) 2013 David Holm <dholmster@gmail.com> # 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. from ...framework.platform import Architecture from ...framework.platform import Cpu from ...framework.platform import Register from ...framework.platform import register_cpu @register_cpu class GenericCpu(Cpu): def
(self, cpu_factory, registers): for group, register_list in registers.iteritems(): registers[group] = [Register(x) for x in register_list] super(GenericCpu, self).__init__(cpu_factory, registers) @classmethod def architecture(cls): return Architecture.Generic def stack_pointer(self): return self.register('sp') def program_counter(self): return self.register('pc')
__init__
identifier_name
comment.py
# -*- coding: utf-8 -*- """ github3.gists.comment --------------------- Module containing the logic for a GistComment """ from __future__ import unicode_literals from ..models import BaseComment from ..users import User class GistComment(BaseComment): """This object represents a comment on a gist. Two comment instances can be checked like so:: c1 == c2 c1 != c2 And is equivalent to:: c1.id == c2.id c1.id != c2.id See also: http://developer.github.com/v3/gists/comments/ """ def _update_attributes(self, comment): self._api = comment.get('url') #: :class:`User <github3.users.User>` who made the comment #: Unless it is not associated with an account self.user = None if comment.get('user'): self.user = User(comment.get('user'), self) # (No coverage) def _repr(self):
return '<Gist Comment [{0}]>'.format(self.user.login)
identifier_body
comment.py
# -*- coding: utf-8 -*- """ github3.gists.comment --------------------- Module containing the logic for a GistComment """ from __future__ import unicode_literals from ..models import BaseComment from ..users import User class GistComment(BaseComment): """This object represents a comment on a gist. Two comment instances can be checked like so:: c1 == c2 c1 != c2 And is equivalent to:: c1.id == c2.id c1.id != c2.id See also: http://developer.github.com/v3/gists/comments/ """ def _update_attributes(self, comment): self._api = comment.get('url') #: :class:`User <github3.users.User>` who made the comment
if comment.get('user'): self.user = User(comment.get('user'), self) # (No coverage) def _repr(self): return '<Gist Comment [{0}]>'.format(self.user.login)
#: Unless it is not associated with an account self.user = None
random_line_split
comment.py
# -*- coding: utf-8 -*- """ github3.gists.comment --------------------- Module containing the logic for a GistComment """ from __future__ import unicode_literals from ..models import BaseComment from ..users import User class GistComment(BaseComment): """This object represents a comment on a gist. Two comment instances can be checked like so:: c1 == c2 c1 != c2 And is equivalent to:: c1.id == c2.id c1.id != c2.id See also: http://developer.github.com/v3/gists/comments/ """ def _update_attributes(self, comment): self._api = comment.get('url') #: :class:`User <github3.users.User>` who made the comment #: Unless it is not associated with an account self.user = None if comment.get('user'):
def _repr(self): return '<Gist Comment [{0}]>'.format(self.user.login)
self.user = User(comment.get('user'), self) # (No coverage)
conditional_block
comment.py
# -*- coding: utf-8 -*- """ github3.gists.comment --------------------- Module containing the logic for a GistComment """ from __future__ import unicode_literals from ..models import BaseComment from ..users import User class GistComment(BaseComment): """This object represents a comment on a gist. Two comment instances can be checked like so:: c1 == c2 c1 != c2 And is equivalent to:: c1.id == c2.id c1.id != c2.id See also: http://developer.github.com/v3/gists/comments/ """ def
(self, comment): self._api = comment.get('url') #: :class:`User <github3.users.User>` who made the comment #: Unless it is not associated with an account self.user = None if comment.get('user'): self.user = User(comment.get('user'), self) # (No coverage) def _repr(self): return '<Gist Comment [{0}]>'.format(self.user.login)
_update_attributes
identifier_name
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn from_u8_singlerule(file: &[u8], rule: &super::MagicRule) -> bool { // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bound_max { return false; } if rule.region_len == 0 { //println!("Region == 0"); match rule.mask { None => { //println!("\tMask == None"); let x: Vec<u8> = file.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); return rule.val.iter().eq(x.iter()); }, Some(ref mask) => { //println!("\tMask == Some, len == {}", mask.len()); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); let mut x: Vec<u8> = file.iter() .skip(bound_min) // Skip to start of area .take(bound_max - bound_min) // Take until end of area - region length .map(|&x| x).collect(); // Convert to vector let mut val: Vec<u8> = rule.val.iter().map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); assert_eq!(x.len(), mask.len()); for i in 0..std::cmp::min(x.len(), mask.len()) { x[i] &= mask[i]; val[i] = val[i] & mask[i]; } //println!("\t & {:?} => {:?}", mask, x); return rule.val.iter().eq(x.iter()); } } } else { //println!("\tRegion == {}", rule.region_len); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); // Define our testing slice let ref x: Vec<u8> = file.iter().take(file.len()).map(|&x| x).collect(); let testarea: Vec<u8> = x.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("{:?}, {:?}, {:?}\n", file, testarea, rule.val); // Search down until we find a hit let mut y = Vec::<u8>::with_capacity(testarea.len()); for x in testarea.windows(rule.val_len as usize) { y.clear(); // Apply mask to value let ref rule_mask = rule.mask; match *rule_mask { Some(ref mask) => { for i in 0..rule.val_len {
y.push(x[i as usize] & mask[i as usize]); } }, None => y = x.to_vec(), } if y.iter().eq(rule.val.iter()) { return true; } } } false } /// Test every given rule by walking graph /// TODO: Not loving the code duplication here. pub fn from_u8_walker( file: &[u8], mimetype: MIME, graph: &DiGraph<super::MagicRule, u32>, node: NodeIndex, isroot: bool ) -> bool { let n = graph.neighbors_directed(node, Outgoing); if isroot { let ref rule = graph[node]; // Check root if !from_u8_singlerule(&file, rule) { return false; } // Return if that was the only test if n.clone().count() == 0 { return true; } // Otherwise next indent level is lower, so continue } // Check subrules recursively for y in n { let ref rule = graph[y]; if from_u8_singlerule(&file, rule) { // Check next indent level if needed if graph.neighbors_directed(y, Outgoing).count() != 0 { return from_u8_walker(file, mimetype, graph, y, false); // Next indent level is lower, so this must be it } else { return true; } } } false }
random_line_split
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn from_u8_singlerule(file: &[u8], rule: &super::MagicRule) -> bool { // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bound_max { return false; } if rule.region_len == 0
else { //println!("\tRegion == {}", rule.region_len); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); // Define our testing slice let ref x: Vec<u8> = file.iter().take(file.len()).map(|&x| x).collect(); let testarea: Vec<u8> = x.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("{:?}, {:?}, {:?}\n", file, testarea, rule.val); // Search down until we find a hit let mut y = Vec::<u8>::with_capacity(testarea.len()); for x in testarea.windows(rule.val_len as usize) { y.clear(); // Apply mask to value let ref rule_mask = rule.mask; match *rule_mask { Some(ref mask) => { for i in 0..rule.val_len { y.push(x[i as usize] & mask[i as usize]); } }, None => y = x.to_vec(), } if y.iter().eq(rule.val.iter()) { return true; } } } false } /// Test every given rule by walking graph /// TODO: Not loving the code duplication here. pub fn from_u8_walker( file: &[u8], mimetype: MIME, graph: &DiGraph<super::MagicRule, u32>, node: NodeIndex, isroot: bool ) -> bool { let n = graph.neighbors_directed(node, Outgoing); if isroot { let ref rule = graph[node]; // Check root if !from_u8_singlerule(&file, rule) { return false; } // Return if that was the only test if n.clone().count() == 0 { return true; } // Otherwise next indent level is lower, so continue } // Check subrules recursively for y in n { let ref rule = graph[y]; if from_u8_singlerule(&file, rule) { // Check next indent level if needed if graph.neighbors_directed(y, Outgoing).count() != 0 { return from_u8_walker(file, mimetype, graph, y, false); // Next indent level is lower, so this must be it } else { return true; } } } false }
{ //println!("Region == 0"); match rule.mask { None => { //println!("\tMask == None"); let x: Vec<u8> = file.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); return rule.val.iter().eq(x.iter()); }, Some(ref mask) => { //println!("\tMask == Some, len == {}", mask.len()); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); let mut x: Vec<u8> = file.iter() .skip(bound_min) // Skip to start of area .take(bound_max - bound_min) // Take until end of area - region length .map(|&x| x).collect(); // Convert to vector let mut val: Vec<u8> = rule.val.iter().map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); assert_eq!(x.len(), mask.len()); for i in 0..std::cmp::min(x.len(), mask.len()) { x[i] &= mask[i]; val[i] = val[i] & mask[i]; } //println!("\t & {:?} => {:?}", mask, x); return rule.val.iter().eq(x.iter()); } } }
conditional_block
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn from_u8_singlerule(file: &[u8], rule: &super::MagicRule) -> bool
/// Test every given rule by walking graph /// TODO: Not loving the code duplication here. pub fn from_u8_walker( file: &[u8], mimetype: MIME, graph: &DiGraph<super::MagicRule, u32>, node: NodeIndex, isroot: bool ) -> bool { let n = graph.neighbors_directed(node, Outgoing); if isroot { let ref rule = graph[node]; // Check root if !from_u8_singlerule(&file, rule) { return false; } // Return if that was the only test if n.clone().count() == 0 { return true; } // Otherwise next indent level is lower, so continue } // Check subrules recursively for y in n { let ref rule = graph[y]; if from_u8_singlerule(&file, rule) { // Check next indent level if needed if graph.neighbors_directed(y, Outgoing).count() != 0 { return from_u8_walker(file, mimetype, graph, y, false); // Next indent level is lower, so this must be it } else { return true; } } } false }
{ // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bound_max { return false; } if rule.region_len == 0 { //println!("Region == 0"); match rule.mask { None => { //println!("\tMask == None"); let x: Vec<u8> = file.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); return rule.val.iter().eq(x.iter()); }, Some(ref mask) => { //println!("\tMask == Some, len == {}", mask.len()); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); let mut x: Vec<u8> = file.iter() .skip(bound_min) // Skip to start of area .take(bound_max - bound_min) // Take until end of area - region length .map(|&x| x).collect(); // Convert to vector let mut val: Vec<u8> = rule.val.iter().map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); assert_eq!(x.len(), mask.len()); for i in 0..std::cmp::min(x.len(), mask.len()) { x[i] &= mask[i]; val[i] = val[i] & mask[i]; } //println!("\t & {:?} => {:?}", mask, x); return rule.val.iter().eq(x.iter()); } } } else { //println!("\tRegion == {}", rule.region_len); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); // Define our testing slice let ref x: Vec<u8> = file.iter().take(file.len()).map(|&x| x).collect(); let testarea: Vec<u8> = x.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("{:?}, {:?}, {:?}\n", file, testarea, rule.val); // Search down until we find a hit let mut y = Vec::<u8>::with_capacity(testarea.len()); for x in testarea.windows(rule.val_len as usize) { y.clear(); // Apply mask to value let ref rule_mask = rule.mask; match *rule_mask { Some(ref mask) => { for i in 0..rule.val_len { y.push(x[i as usize] & mask[i as usize]); } }, None => y = x.to_vec(), } if y.iter().eq(rule.val.iter()) { return true; } } } false }
identifier_body
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn
(file: &[u8], rule: &super::MagicRule) -> bool { // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bound_max { return false; } if rule.region_len == 0 { //println!("Region == 0"); match rule.mask { None => { //println!("\tMask == None"); let x: Vec<u8> = file.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); return rule.val.iter().eq(x.iter()); }, Some(ref mask) => { //println!("\tMask == Some, len == {}", mask.len()); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); let mut x: Vec<u8> = file.iter() .skip(bound_min) // Skip to start of area .take(bound_max - bound_min) // Take until end of area - region length .map(|&x| x).collect(); // Convert to vector let mut val: Vec<u8> = rule.val.iter().map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); assert_eq!(x.len(), mask.len()); for i in 0..std::cmp::min(x.len(), mask.len()) { x[i] &= mask[i]; val[i] = val[i] & mask[i]; } //println!("\t & {:?} => {:?}", mask, x); return rule.val.iter().eq(x.iter()); } } } else { //println!("\tRegion == {}", rule.region_len); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); // Define our testing slice let ref x: Vec<u8> = file.iter().take(file.len()).map(|&x| x).collect(); let testarea: Vec<u8> = x.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("{:?}, {:?}, {:?}\n", file, testarea, rule.val); // Search down until we find a hit let mut y = Vec::<u8>::with_capacity(testarea.len()); for x in testarea.windows(rule.val_len as usize) { y.clear(); // Apply mask to value let ref rule_mask = rule.mask; match *rule_mask { Some(ref mask) => { for i in 0..rule.val_len { y.push(x[i as usize] & mask[i as usize]); } }, None => y = x.to_vec(), } if y.iter().eq(rule.val.iter()) { return true; } } } false } /// Test every given rule by walking graph /// TODO: Not loving the code duplication here. pub fn from_u8_walker( file: &[u8], mimetype: MIME, graph: &DiGraph<super::MagicRule, u32>, node: NodeIndex, isroot: bool ) -> bool { let n = graph.neighbors_directed(node, Outgoing); if isroot { let ref rule = graph[node]; // Check root if !from_u8_singlerule(&file, rule) { return false; } // Return if that was the only test if n.clone().count() == 0 { return true; } // Otherwise next indent level is lower, so continue } // Check subrules recursively for y in n { let ref rule = graph[y]; if from_u8_singlerule(&file, rule) { // Check next indent level if needed if graph.neighbors_directed(y, Outgoing).count() != 0 { return from_u8_walker(file, mimetype, graph, y, false); // Next indent level is lower, so this must be it } else { return true; } } } false }
from_u8_singlerule
identifier_name
stats.py
import bench class Stats(bench.Bench): def __init__(self, league): bench.Bench.__init__(self) self.league = league self.type = 'stats' def list(self, team=False, player=False): """ Lists all stats for the current season to date. Can be filtered by team or by player. Default will return stat dump for whole league :param team: Unique ID of the team to filter for :param player: Unique ID of the player to filter for
""" Lists the stat breakdown by week for a given player. Can also be filtered to only return a specific week or a range of weeks :param player: Unique ID of the player to filter for :param week: Optional. Can be a single week or a range ex: 1-4. If blank will default to season to date :return: """
:return: """ def get_player_stats(self, player, week=False):
random_line_split
stats.py
import bench class Stats(bench.Bench):
def __init__(self, league): bench.Bench.__init__(self) self.league = league self.type = 'stats' def list(self, team=False, player=False): """ Lists all stats for the current season to date. Can be filtered by team or by player. Default will return stat dump for whole league :param team: Unique ID of the team to filter for :param player: Unique ID of the player to filter for :return: """ def get_player_stats(self, player, week=False): """ Lists the stat breakdown by week for a given player. Can also be filtered to only return a specific week or a range of weeks :param player: Unique ID of the player to filter for :param week: Optional. Can be a single week or a range ex: 1-4. If blank will default to season to date :return: """
identifier_body
stats.py
import bench class Stats(bench.Bench): def __init__(self, league): bench.Bench.__init__(self) self.league = league self.type = 'stats' def
(self, team=False, player=False): """ Lists all stats for the current season to date. Can be filtered by team or by player. Default will return stat dump for whole league :param team: Unique ID of the team to filter for :param player: Unique ID of the player to filter for :return: """ def get_player_stats(self, player, week=False): """ Lists the stat breakdown by week for a given player. Can also be filtered to only return a specific week or a range of weeks :param player: Unique ID of the player to filter for :param week: Optional. Can be a single week or a range ex: 1-4. If blank will default to season to date :return: """
list
identifier_name
lifetime.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::region; use rustc::middle::ty; use rustc::util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { //! Reports error if `loan_region` is larger than S //! where S is `item_scope` if `cmt` is an upvar, //! and is scope of `cmt` otherwise. debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope: item_scope, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, // the scope of the function body for the enclosing item item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt<'tcx> } impl<'a, 'tcx> GuaranteeLifetimeContext<'a, 'tcx> { fn check(&self, cmt: &mc::cmt<'tcx>, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the //! "guarantor". Reports an error if `self.loan_region` is //! larger than scope of `cmt`. debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_local(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base, _) | mc::cat_deref(ref base, _, mc::Unique) | // L-Deref-Send mc::cat_interior(ref base, _) => { // L-Field self.check(base, discr_scope) } } } fn check_scope(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `max_scope` if !self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) => { ty::ReScope(self.item_scope) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) =>
mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt, _) | mc::cat_deref(ref cmt, _, mc::Unique) | mc::cat_interior(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
{ ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) }
conditional_block
lifetime.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::region; use rustc::middle::ty; use rustc::util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { //! Reports error if `loan_region` is larger than S //! where S is `item_scope` if `cmt` is an upvar, //! and is scope of `cmt` otherwise. debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope: item_scope, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, // the scope of the function body for the enclosing item item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt<'tcx> } impl<'a, 'tcx> GuaranteeLifetimeContext<'a, 'tcx> { fn check(&self, cmt: &mc::cmt<'tcx>, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the //! "guarantor". Reports an error if `self.loan_region` is //! larger than scope of `cmt`. debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_local(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base, _) | mc::cat_deref(ref base, _, mc::Unique) | // L-Deref-Send mc::cat_interior(ref base, _) => { // L-Field self.check(base, discr_scope) } } } fn check_scope(&self, max_scope: ty::Region) -> R
fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) => { ty::ReScope(self.item_scope) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt, _) | mc::cat_deref(ref cmt, _, mc::Unique) | mc::cat_interior(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
{ //! Reports an error if `loan_region` is larger than `max_scope` if !self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } }
identifier_body
lifetime.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::region; use rustc::middle::ty; use rustc::util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { //! Reports error if `loan_region` is larger than S //! where S is `item_scope` if `cmt` is an upvar, //! and is scope of `cmt` otherwise. debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope: item_scope, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, // the scope of the function body for the enclosing item item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt<'tcx> } impl<'a, 'tcx> GuaranteeLifetimeContext<'a, 'tcx> { fn check(&self, cmt: &mc::cmt<'tcx>, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the //! "guarantor". Reports an error if `self.loan_region` is //! larger than scope of `cmt`. debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_local(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base, _) | mc::cat_deref(ref base, _, mc::Unique) | // L-Deref-Send mc::cat_interior(ref base, _) => { // L-Field self.check(base, discr_scope) } } } fn
(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `max_scope` if !self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) => { ty::ReScope(self.item_scope) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt, _) | mc::cat_deref(ref cmt, _, mc::Unique) | mc::cat_interior(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
check_scope
identifier_name
lifetime.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::region; use rustc::middle::ty; use rustc::util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { //! Reports error if `loan_region` is larger than S //! where S is `item_scope` if `cmt` is an upvar, //! and is scope of `cmt` otherwise. debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope: item_scope, span: span, cause: cause, loan_region: loan_region,
cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, // the scope of the function body for the enclosing item item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt<'tcx> } impl<'a, 'tcx> GuaranteeLifetimeContext<'a, 'tcx> { fn check(&self, cmt: &mc::cmt<'tcx>, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the //! "guarantor". Reports an error if `self.loan_region` is //! larger than scope of `cmt`. debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_local(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base, _) | mc::cat_deref(ref base, _, mc::Unique) | // L-Deref-Send mc::cat_interior(ref base, _) => { // L-Field self.check(base, discr_scope) } } } fn check_scope(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `max_scope` if !self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) => { ty::ReScope(self.item_scope) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt, _) | mc::cat_deref(ref cmt, _, mc::Unique) | mc::cat_interior(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
random_line_split
specialization-basics.rs
// run-pass #![feature(specialization)] //~ WARN the feature `specialization` is incomplete // Tests a variety of basic specialization scenarios and method // dispatch for them. trait Foo { fn foo(&self) -> &'static str; } impl<T> Foo for T { default fn foo(&self) -> &'static str { "generic" } } impl<T: Clone> Foo for T { default fn foo(&self) -> &'static str { "generic Clone" } } impl<T, U> Foo for (T, U) where T: Clone, U: Clone { default fn foo(&self) -> &'static str { "generic pair" } } impl<T: Clone> Foo for (T, T) { default fn foo(&self) -> &'static str { "generic uniform pair" } } impl Foo for (u8, u32) { default fn foo(&self) -> &'static str { "(u8, u32)" } } impl Foo for (u8, u8) { default fn foo(&self) -> &'static str { "(u8, u8)" } } impl<T: Clone> Foo for Vec<T> { default fn foo(&self) -> &'static str { "generic Vec" } } impl Foo for Vec<i32> { fn foo(&self) -> &'static str { "Vec<i32>" } } impl Foo for String { fn foo(&self) -> &'static str { "String" } } impl Foo for i32 { fn foo(&self) -> &'static str { "i32" } } struct NotClone; trait MyMarker {} impl<T: Clone + MyMarker> Foo for T { default fn foo(&self) -> &'static str { "generic Clone + MyMarker" } } #[derive(Clone)]
assert!(NotClone.foo() == "generic"); assert!(0u8.foo() == "generic Clone"); assert!(vec![NotClone].foo() == "generic"); assert!(vec![0u8].foo() == "generic Vec"); assert!(vec![0i32].foo() == "Vec<i32>"); assert!(0i32.foo() == "i32"); assert!(String::new().foo() == "String"); assert!(((), 0).foo() == "generic pair"); assert!(((), ()).foo() == "generic uniform pair"); assert!((0u8, 0u32).foo() == "(u8, u32)"); assert!((0u8, 0u8).foo() == "(u8, u8)"); assert!(MarkedAndClone.foo() == "generic Clone + MyMarker"); }
struct MarkedAndClone; impl MyMarker for MarkedAndClone {} fn main() {
random_line_split
specialization-basics.rs
// run-pass #![feature(specialization)] //~ WARN the feature `specialization` is incomplete // Tests a variety of basic specialization scenarios and method // dispatch for them. trait Foo { fn foo(&self) -> &'static str; } impl<T> Foo for T { default fn foo(&self) -> &'static str { "generic" } } impl<T: Clone> Foo for T { default fn foo(&self) -> &'static str { "generic Clone" } } impl<T, U> Foo for (T, U) where T: Clone, U: Clone { default fn foo(&self) -> &'static str { "generic pair" } } impl<T: Clone> Foo for (T, T) { default fn foo(&self) -> &'static str { "generic uniform pair" } } impl Foo for (u8, u32) { default fn foo(&self) -> &'static str { "(u8, u32)" } } impl Foo for (u8, u8) { default fn
(&self) -> &'static str { "(u8, u8)" } } impl<T: Clone> Foo for Vec<T> { default fn foo(&self) -> &'static str { "generic Vec" } } impl Foo for Vec<i32> { fn foo(&self) -> &'static str { "Vec<i32>" } } impl Foo for String { fn foo(&self) -> &'static str { "String" } } impl Foo for i32 { fn foo(&self) -> &'static str { "i32" } } struct NotClone; trait MyMarker {} impl<T: Clone + MyMarker> Foo for T { default fn foo(&self) -> &'static str { "generic Clone + MyMarker" } } #[derive(Clone)] struct MarkedAndClone; impl MyMarker for MarkedAndClone {} fn main() { assert!(NotClone.foo() == "generic"); assert!(0u8.foo() == "generic Clone"); assert!(vec![NotClone].foo() == "generic"); assert!(vec![0u8].foo() == "generic Vec"); assert!(vec![0i32].foo() == "Vec<i32>"); assert!(0i32.foo() == "i32"); assert!(String::new().foo() == "String"); assert!(((), 0).foo() == "generic pair"); assert!(((), ()).foo() == "generic uniform pair"); assert!((0u8, 0u32).foo() == "(u8, u32)"); assert!((0u8, 0u8).foo() == "(u8, u8)"); assert!(MarkedAndClone.foo() == "generic Clone + MyMarker"); }
foo
identifier_name
specialization-basics.rs
// run-pass #![feature(specialization)] //~ WARN the feature `specialization` is incomplete // Tests a variety of basic specialization scenarios and method // dispatch for them. trait Foo { fn foo(&self) -> &'static str; } impl<T> Foo for T { default fn foo(&self) -> &'static str { "generic" } } impl<T: Clone> Foo for T { default fn foo(&self) -> &'static str { "generic Clone" } } impl<T, U> Foo for (T, U) where T: Clone, U: Clone { default fn foo(&self) -> &'static str { "generic pair" } } impl<T: Clone> Foo for (T, T) { default fn foo(&self) -> &'static str { "generic uniform pair" } } impl Foo for (u8, u32) { default fn foo(&self) -> &'static str { "(u8, u32)" } } impl Foo for (u8, u8) { default fn foo(&self) -> &'static str { "(u8, u8)" } } impl<T: Clone> Foo for Vec<T> { default fn foo(&self) -> &'static str { "generic Vec" } } impl Foo for Vec<i32> { fn foo(&self) -> &'static str { "Vec<i32>" } } impl Foo for String { fn foo(&self) -> &'static str { "String" } } impl Foo for i32 { fn foo(&self) -> &'static str
} struct NotClone; trait MyMarker {} impl<T: Clone + MyMarker> Foo for T { default fn foo(&self) -> &'static str { "generic Clone + MyMarker" } } #[derive(Clone)] struct MarkedAndClone; impl MyMarker for MarkedAndClone {} fn main() { assert!(NotClone.foo() == "generic"); assert!(0u8.foo() == "generic Clone"); assert!(vec![NotClone].foo() == "generic"); assert!(vec![0u8].foo() == "generic Vec"); assert!(vec![0i32].foo() == "Vec<i32>"); assert!(0i32.foo() == "i32"); assert!(String::new().foo() == "String"); assert!(((), 0).foo() == "generic pair"); assert!(((), ()).foo() == "generic uniform pair"); assert!((0u8, 0u32).foo() == "(u8, u32)"); assert!((0u8, 0u8).foo() == "(u8, u8)"); assert!(MarkedAndClone.foo() == "generic Clone + MyMarker"); }
{ "i32" }
identifier_body
setup.py
from __future__ import print_function from setuptools import setup import sys if sys.version_info < (2, 6): print('google-api-python-client requires python version >= 2.6.', file = sys.stderr) sys.exit(1) install_requires = ['google-api-python-client==1.3.1'] if sys.version_info < (2, 7): install_requires.append('argparse') setup( name = 'android-publish-cli', packages = [], version = '0.1.2', description = 'A simple CLI for Google Play Publish API', author = 'Spreaker', author_email = 'dev@spreaker.com', url = 'https://github.com/spreaker/android-publish-cli', download_url = 'https://github.com/spreaker/android-publish-cli/tarball/0.1.2',
keywords = ['android', 'automation', 'google'], classifiers = [], install_requires = install_requires, scripts = ['bin/android-publish'] )
random_line_split
setup.py
from __future__ import print_function from setuptools import setup import sys if sys.version_info < (2, 6):
install_requires = ['google-api-python-client==1.3.1'] if sys.version_info < (2, 7): install_requires.append('argparse') setup( name = 'android-publish-cli', packages = [], version = '0.1.2', description = 'A simple CLI for Google Play Publish API', author = 'Spreaker', author_email = 'dev@spreaker.com', url = 'https://github.com/spreaker/android-publish-cli', download_url = 'https://github.com/spreaker/android-publish-cli/tarball/0.1.2', keywords = ['android', 'automation', 'google'], classifiers = [], install_requires = install_requires, scripts = ['bin/android-publish'] )
print('google-api-python-client requires python version >= 2.6.', file = sys.stderr) sys.exit(1)
conditional_block
Opacity.js
/* =============================================================================================== Unify Project Homepage: unify-project.org License: MIT + Apache (V2) Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com =============================================================================================== */ /** * Animate position of widget */ core.Class("unify.fx.Opacity", { include: [unify.fx.core.Base], construct : function(widget) { unify.fx.core.Base.call(this, widget); }, members : { __mod : null, __anim : null, __resetPoint: null, _setup : function() { var to = this.getValue(); var from = this.__resetPoint = parseFloat(this._widget.getStyle("opacity")) || 1; this.__mod = from; this.__anim = to - from }, _reset : function(value) { this._widget.setStyle({ opacity: value||"1" }); }, _getResetValue : function() { return this.__resetPoint; }, _render : function(percent, now, render) { if (!render)
var mod = this.__mod; var anim = this.__anim; this._widget.setStyle({ opacity: (mod + anim * percent) }); } } });
{ return; }
conditional_block
Opacity.js
/* =============================================================================================== Unify Project Homepage: unify-project.org License: MIT + Apache (V2) Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com =============================================================================================== */ /** * Animate position of widget */ core.Class("unify.fx.Opacity", { include: [unify.fx.core.Base], construct : function(widget) { unify.fx.core.Base.call(this, widget); }, members : { __mod : null,
__resetPoint: null, _setup : function() { var to = this.getValue(); var from = this.__resetPoint = parseFloat(this._widget.getStyle("opacity")) || 1; this.__mod = from; this.__anim = to - from }, _reset : function(value) { this._widget.setStyle({ opacity: value||"1" }); }, _getResetValue : function() { return this.__resetPoint; }, _render : function(percent, now, render) { if (!render) { return; } var mod = this.__mod; var anim = this.__anim; this._widget.setStyle({ opacity: (mod + anim * percent) }); } } });
__anim : null,
random_line_split
cache_prefetcher.py
#!/usr/bin/env python # Copyright 2011-2012 OpenStack Foundation # 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. """ Glance Image Cache Pre-fetcher This is meant to be run from the command line after queueing images to be pretched. """ import os import sys # If ../glance/__init__.py exists, add ../ to Python search path, so that # it will override what happens to be installed in /usr/(local/)lib/python... possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')): sys.path.insert(0, possible_topdir) import glance_store from oslo_log import log as logging from glance.common import config from glance.image_cache import prefetcher CONF = config.CONF logging.register_options(CONF) CONF.set_default(name='use_stderr', default=True) def main():
if __name__ == '__main__': main()
try: config.parse_cache_args() logging.setup(CONF, 'glance') glance_store.register_opts(config.CONF) glance_store.create_stores(config.CONF) glance_store.verify_default_store() app = prefetcher.Prefetcher() app.run() except RuntimeError as e: sys.exit("ERROR: %s" % e)
identifier_body
cache_prefetcher.py
#!/usr/bin/env python # Copyright 2011-2012 OpenStack Foundation # 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. """ Glance Image Cache Pre-fetcher This is meant to be run from the command line after queueing images to be pretched. """ import os import sys # If ../glance/__init__.py exists, add ../ to Python search path, so that # it will override what happens to be installed in /usr/(local/)lib/python... possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')): sys.path.insert(0, possible_topdir) import glance_store from oslo_log import log as logging from glance.common import config from glance.image_cache import prefetcher CONF = config.CONF logging.register_options(CONF) CONF.set_default(name='use_stderr', default=True) def main():
config.parse_cache_args() logging.setup(CONF, 'glance') glance_store.register_opts(config.CONF) glance_store.create_stores(config.CONF) glance_store.verify_default_store() app = prefetcher.Prefetcher() app.run() except RuntimeError as e: sys.exit("ERROR: %s" % e) if __name__ == '__main__': main()
try:
random_line_split
cache_prefetcher.py
#!/usr/bin/env python # Copyright 2011-2012 OpenStack Foundation # 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. """ Glance Image Cache Pre-fetcher This is meant to be run from the command line after queueing images to be pretched. """ import os import sys # If ../glance/__init__.py exists, add ../ to Python search path, so that # it will override what happens to be installed in /usr/(local/)lib/python... possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')): sys.path.insert(0, possible_topdir) import glance_store from oslo_log import log as logging from glance.common import config from glance.image_cache import prefetcher CONF = config.CONF logging.register_options(CONF) CONF.set_default(name='use_stderr', default=True) def main(): try: config.parse_cache_args() logging.setup(CONF, 'glance') glance_store.register_opts(config.CONF) glance_store.create_stores(config.CONF) glance_store.verify_default_store() app = prefetcher.Prefetcher() app.run() except RuntimeError as e: sys.exit("ERROR: %s" % e) if __name__ == '__main__':
main()
conditional_block
cache_prefetcher.py
#!/usr/bin/env python # Copyright 2011-2012 OpenStack Foundation # 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. """ Glance Image Cache Pre-fetcher This is meant to be run from the command line after queueing images to be pretched. """ import os import sys # If ../glance/__init__.py exists, add ../ to Python search path, so that # it will override what happens to be installed in /usr/(local/)lib/python... possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')): sys.path.insert(0, possible_topdir) import glance_store from oslo_log import log as logging from glance.common import config from glance.image_cache import prefetcher CONF = config.CONF logging.register_options(CONF) CONF.set_default(name='use_stderr', default=True) def
(): try: config.parse_cache_args() logging.setup(CONF, 'glance') glance_store.register_opts(config.CONF) glance_store.create_stores(config.CONF) glance_store.verify_default_store() app = prefetcher.Prefetcher() app.run() except RuntimeError as e: sys.exit("ERROR: %s" % e) if __name__ == '__main__': main()
main
identifier_name
checkJSPluginExist.js
/* * This code it's help you to check JS plugin function (e.g. jQuery) exist. * When function not exist, the code will auto reload JS plugin from your setting. * * plugin_name: It's your plugin function name (e.g. jQuery). The type is string. * reload_url: It's your reload plugin function URL. The type is string. * * Copyright 2015, opoepev (Matt, Paul.Lu, Yi-Chun Lu) * Free to use and abuse under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ //Main code var checkJSPluginExist = function (plugin_name, reload_url, depend_plugin_name) { //window[plugin_name] || document.write('<script src="' + reload_url + '">\x3C/script>'); if (typeof depend_plugin_name !== 'undefined') { if (typeof window[depend_plugin_name][plugin_name] !== "function") { var tag = document.createElement('script'); tag.src = reload_url; var headerElementTag = document.getElementsByTagName('head')[0]; headerElementTag.appendChild(tag); return false; } } else { if (typeof window[plugin_name] !== "function") { var tag = document.createElement('script'); tag.src = reload_url;
return true; };
var headerElementTag = document.getElementsByTagName('head')[0]; headerElementTag.appendChild(tag); return false; } }
random_line_split
checkJSPluginExist.js
/* * This code it's help you to check JS plugin function (e.g. jQuery) exist. * When function not exist, the code will auto reload JS plugin from your setting. * * plugin_name: It's your plugin function name (e.g. jQuery). The type is string. * reload_url: It's your reload plugin function URL. The type is string. * * Copyright 2015, opoepev (Matt, Paul.Lu, Yi-Chun Lu) * Free to use and abuse under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ //Main code var checkJSPluginExist = function (plugin_name, reload_url, depend_plugin_name) { //window[plugin_name] || document.write('<script src="' + reload_url + '">\x3C/script>'); if (typeof depend_plugin_name !== 'undefined') { if (typeof window[depend_plugin_name][plugin_name] !== "function") { var tag = document.createElement('script'); tag.src = reload_url; var headerElementTag = document.getElementsByTagName('head')[0]; headerElementTag.appendChild(tag); return false; } } else
return true; };
{ if (typeof window[plugin_name] !== "function") { var tag = document.createElement('script'); tag.src = reload_url; var headerElementTag = document.getElementsByTagName('head')[0]; headerElementTag.appendChild(tag); return false; } }
conditional_block
Navigation.tsx
import React, {useEffect} from "react"; import {HomeView} from "./Home"; import Resume from "./Resume"; import {NavLink, Route} from "react-router-dom"; import Contact from "./Contact"; type RouteDef = { title: string; path: string; component: React.ReactNode } const routeDefs: RouteDef[] = [ { title: "Home", path: "/", component: HomeView }, { title: "Resume", path: "/resume", component: Resume }, { title: "Contact", path: "/contact", component: Contact } ] export const routes = routeDefs.map(rd => { return <Route key={rd.title} exact path={rd.path} component={() => { useDocumentTitle(rd.title); return <rd.component/>; }} />; }); const navLinks = routeDefs.map(rd => { return <NavLink key={rd.title} exact to={rd.path} className="px-1" activeClassName="border-b border-indigo-400 text-indigo-500"> {rd.title} </NavLink> }); export default function
() { return <div className="flex flex-row justify-center gap-2 text-xl mb-8"> {navLinks} </div> } function useDocumentTitle(title: string): void { useEffect(() => { window.document.title = (title ? `${title} - mattbague` : "mattbague") }, [title]); }
Navigation
identifier_name
Navigation.tsx
import React, {useEffect} from "react"; import {HomeView} from "./Home"; import Resume from "./Resume"; import {NavLink, Route} from "react-router-dom"; import Contact from "./Contact"; type RouteDef = { title: string; path: string; component: React.ReactNode
title: "Home", path: "/", component: HomeView }, { title: "Resume", path: "/resume", component: Resume }, { title: "Contact", path: "/contact", component: Contact } ] export const routes = routeDefs.map(rd => { return <Route key={rd.title} exact path={rd.path} component={() => { useDocumentTitle(rd.title); return <rd.component/>; }} />; }); const navLinks = routeDefs.map(rd => { return <NavLink key={rd.title} exact to={rd.path} className="px-1" activeClassName="border-b border-indigo-400 text-indigo-500"> {rd.title} </NavLink> }); export default function Navigation() { return <div className="flex flex-row justify-center gap-2 text-xl mb-8"> {navLinks} </div> } function useDocumentTitle(title: string): void { useEffect(() => { window.document.title = (title ? `${title} - mattbague` : "mattbague") }, [title]); }
} const routeDefs: RouteDef[] = [ {
random_line_split
Navigation.tsx
import React, {useEffect} from "react"; import {HomeView} from "./Home"; import Resume from "./Resume"; import {NavLink, Route} from "react-router-dom"; import Contact from "./Contact"; type RouteDef = { title: string; path: string; component: React.ReactNode } const routeDefs: RouteDef[] = [ { title: "Home", path: "/", component: HomeView }, { title: "Resume", path: "/resume", component: Resume }, { title: "Contact", path: "/contact", component: Contact } ] export const routes = routeDefs.map(rd => { return <Route key={rd.title} exact path={rd.path} component={() => { useDocumentTitle(rd.title); return <rd.component/>; }} />; }); const navLinks = routeDefs.map(rd => { return <NavLink key={rd.title} exact to={rd.path} className="px-1" activeClassName="border-b border-indigo-400 text-indigo-500"> {rd.title} </NavLink> }); export default function Navigation() { return <div className="flex flex-row justify-center gap-2 text-xl mb-8"> {navLinks} </div> } function useDocumentTitle(title: string): void
{ useEffect(() => { window.document.title = (title ? `${title} - mattbague` : "mattbague") }, [title]); }
identifier_body
sample.rs
use ffi::*; use caps::Caps; use buffer::Buffer; use videoframe::VideoFrame; use std::mem; use std::ptr; use reference::Reference; use miniobject::MiniObject; unsafe impl Send for Sample {} #[derive(Clone)] pub struct Sample{ sample: MiniObject } impl Sample{ pub unsafe fn new(sample: *mut GstSample) -> Option<Sample>{ MiniObject::new_from_gst_miniobject(sample as *mut GstMiniObject) .map(|miniobject| Sample{ sample: miniobject }) } /// Get the buffer associated with sample or None when there is no buffer. pub fn
(&self) -> Option<Buffer>{ unsafe{ let buffer = gst_sample_get_buffer(mem::transmute(self.gst_sample())); if buffer != ptr::null_mut(){ Buffer::new(gst_mini_object_ref(buffer as *mut GstMiniObject) as *mut GstBuffer) }else{ None } } } /// Get the caps associated with sample or None when there's no caps pub fn caps(&self) -> Option<Caps>{ unsafe{ let caps = gst_sample_get_caps(mem::transmute(self.gst_sample())); if caps != ptr::null_mut(){ Caps::new(gst_mini_object_ref(caps as *mut GstMiniObject) as *mut GstCaps) }else{ None } } } /// Get the segment associated with sample pub fn segment(&self) -> GstSegment{ unsafe{ (*gst_sample_get_segment(mem::transmute(self.gst_sample()))) } } /// Get a video frame from this sample if it contains one pub fn video_frame(&self) -> Option<VideoFrame>{ let buffer = match self.buffer(){ Some(buffer) => buffer, None => return None }; let vi = match self.caps(){ Some(caps) => match caps.video_info(){ Some(vi) => vi, None => return None }, None => return None }; unsafe{ VideoFrame::new(vi, buffer) } } pub unsafe fn gst_sample(&self) -> *const GstSample{ self.sample.gst_miniobject() as *const GstSample } pub unsafe fn gst_sample_mut(&mut self) -> *mut GstSample{ self.sample.gst_miniobject_mut() as *mut GstSample } } impl ::Transfer<GstSample> for Sample{ unsafe fn transfer(self) -> *mut GstSample{ self.sample.transfer() as *mut GstSample } } impl Reference for Sample{ fn reference(&self) -> Sample{ Sample{ sample: self.sample.reference() } } }
buffer
identifier_name
sample.rs
use ffi::*; use caps::Caps; use buffer::Buffer; use videoframe::VideoFrame; use std::mem; use std::ptr; use reference::Reference; use miniobject::MiniObject; unsafe impl Send for Sample {} #[derive(Clone)] pub struct Sample{ sample: MiniObject } impl Sample{ pub unsafe fn new(sample: *mut GstSample) -> Option<Sample>{ MiniObject::new_from_gst_miniobject(sample as *mut GstMiniObject) .map(|miniobject| Sample{ sample: miniobject }) } /// Get the buffer associated with sample or None when there is no buffer. pub fn buffer(&self) -> Option<Buffer>{ unsafe{ let buffer = gst_sample_get_buffer(mem::transmute(self.gst_sample())); if buffer != ptr::null_mut(){ Buffer::new(gst_mini_object_ref(buffer as *mut GstMiniObject) as *mut GstBuffer) }else{ None } } } /// Get the caps associated with sample or None when there's no caps pub fn caps(&self) -> Option<Caps>
/// Get the segment associated with sample pub fn segment(&self) -> GstSegment{ unsafe{ (*gst_sample_get_segment(mem::transmute(self.gst_sample()))) } } /// Get a video frame from this sample if it contains one pub fn video_frame(&self) -> Option<VideoFrame>{ let buffer = match self.buffer(){ Some(buffer) => buffer, None => return None }; let vi = match self.caps(){ Some(caps) => match caps.video_info(){ Some(vi) => vi, None => return None }, None => return None }; unsafe{ VideoFrame::new(vi, buffer) } } pub unsafe fn gst_sample(&self) -> *const GstSample{ self.sample.gst_miniobject() as *const GstSample } pub unsafe fn gst_sample_mut(&mut self) -> *mut GstSample{ self.sample.gst_miniobject_mut() as *mut GstSample } } impl ::Transfer<GstSample> for Sample{ unsafe fn transfer(self) -> *mut GstSample{ self.sample.transfer() as *mut GstSample } } impl Reference for Sample{ fn reference(&self) -> Sample{ Sample{ sample: self.sample.reference() } } }
{ unsafe{ let caps = gst_sample_get_caps(mem::transmute(self.gst_sample())); if caps != ptr::null_mut(){ Caps::new(gst_mini_object_ref(caps as *mut GstMiniObject) as *mut GstCaps) }else{ None } } }
identifier_body
sample.rs
use ffi::*; use caps::Caps; use buffer::Buffer; use videoframe::VideoFrame; use std::mem; use std::ptr; use reference::Reference; use miniobject::MiniObject; unsafe impl Send for Sample {} #[derive(Clone)] pub struct Sample{ sample: MiniObject } impl Sample{ pub unsafe fn new(sample: *mut GstSample) -> Option<Sample>{ MiniObject::new_from_gst_miniobject(sample as *mut GstMiniObject) .map(|miniobject| Sample{ sample: miniobject }) } /// Get the buffer associated with sample or None when there is no buffer. pub fn buffer(&self) -> Option<Buffer>{ unsafe{ let buffer = gst_sample_get_buffer(mem::transmute(self.gst_sample())); if buffer != ptr::null_mut(){ Buffer::new(gst_mini_object_ref(buffer as *mut GstMiniObject) as *mut GstBuffer) }else{ None } } } /// Get the caps associated with sample or None when there's no caps pub fn caps(&self) -> Option<Caps>{ unsafe{ let caps = gst_sample_get_caps(mem::transmute(self.gst_sample())); if caps != ptr::null_mut(){ Caps::new(gst_mini_object_ref(caps as *mut GstMiniObject) as *mut GstCaps) }else{ None } } } /// Get the segment associated with sample pub fn segment(&self) -> GstSegment{ unsafe{ (*gst_sample_get_segment(mem::transmute(self.gst_sample()))) } } /// Get a video frame from this sample if it contains one pub fn video_frame(&self) -> Option<VideoFrame>{ let buffer = match self.buffer(){ Some(buffer) => buffer, None => return None }; let vi = match self.caps(){ Some(caps) => match caps.video_info(){ Some(vi) => vi, None => return None }, None => return None }; unsafe{ VideoFrame::new(vi, buffer) } } pub unsafe fn gst_sample(&self) -> *const GstSample{ self.sample.gst_miniobject() as *const GstSample } pub unsafe fn gst_sample_mut(&mut self) -> *mut GstSample{ self.sample.gst_miniobject_mut() as *mut GstSample } } impl ::Transfer<GstSample> for Sample{ unsafe fn transfer(self) -> *mut GstSample{
impl Reference for Sample{ fn reference(&self) -> Sample{ Sample{ sample: self.sample.reference() } } }
self.sample.transfer() as *mut GstSample } }
random_line_split
user-permissions.action.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ import {Action} from '@ngrx/store'; import {AllowedPermissions, AllowedPermissionsMap} from '../../model/allowed-permissions'; export enum UserPermissionsActionType { SET_ORGANIZATION_PERMISSIONS = '[User Permissions] Set Organization Permissions', SET_ORGANIZATIONS_PERMISSIONS = '[User Permissions] Set Organizations Permissions', SET_PROJECT_PERMISSIONS = '[User Permissions] Set Project Permissions', SET_PROJECTS_PERMISSIONS = '[User Permissions] Set Projects Permissions', SET_COLLECTIONS_PERMISSIONS = '[User Permissions] Set Collections Permissions', SET_LINK_TYPES_PERMISSIONS = '[User Permissions] Set LinkTypes Permissions', SET_VIEWS_PERMISSIONS = '[User Permissions] Set Views Permissions', CLEAR = '[User Permissions] Clear', } export namespace UserPermissionsAction { export class SetOrganizationPermissions implements Action { public readonly type = UserPermissionsActionType.SET_ORGANIZATION_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissions}) {} } export class SetProjectPermissions implements Action { public readonly type = UserPermissionsActionType.SET_PROJECT_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissions}) {} }
public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class SetProjectsPermissions implements Action { public readonly type = UserPermissionsActionType.SET_PROJECTS_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class SetCollectionsPermissions implements Action { public readonly type = UserPermissionsActionType.SET_COLLECTIONS_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class SetLinkTypesPermissions implements Action { public readonly type = UserPermissionsActionType.SET_LINK_TYPES_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class SetViewsPermissions implements Action { public readonly type = UserPermissionsActionType.SET_VIEWS_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class Clear implements Action { public readonly type = UserPermissionsActionType.CLEAR; } export type All = | SetOrganizationPermissions | SetOrganizationsPermissions | SetProjectPermissions | SetProjectsPermissions | SetCollectionsPermissions | SetLinkTypesPermissions | SetViewsPermissions | Clear; }
export class SetOrganizationsPermissions implements Action { public readonly type = UserPermissionsActionType.SET_ORGANIZATIONS_PERMISSIONS;
random_line_split
user-permissions.action.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ import {Action} from '@ngrx/store'; import {AllowedPermissions, AllowedPermissionsMap} from '../../model/allowed-permissions'; export enum UserPermissionsActionType { SET_ORGANIZATION_PERMISSIONS = '[User Permissions] Set Organization Permissions', SET_ORGANIZATIONS_PERMISSIONS = '[User Permissions] Set Organizations Permissions', SET_PROJECT_PERMISSIONS = '[User Permissions] Set Project Permissions', SET_PROJECTS_PERMISSIONS = '[User Permissions] Set Projects Permissions', SET_COLLECTIONS_PERMISSIONS = '[User Permissions] Set Collections Permissions', SET_LINK_TYPES_PERMISSIONS = '[User Permissions] Set LinkTypes Permissions', SET_VIEWS_PERMISSIONS = '[User Permissions] Set Views Permissions', CLEAR = '[User Permissions] Clear', } export namespace UserPermissionsAction { export class SetOrganizationPermissions implements Action { public readonly type = UserPermissionsActionType.SET_ORGANIZATION_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissions}) {} } export class SetProjectPermissions implements Action { public readonly type = UserPermissionsActionType.SET_PROJECT_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissions}) {} } export class SetOrganizationsPermissions implements Action { public readonly type = UserPermissionsActionType.SET_ORGANIZATIONS_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class SetProjectsPermissions implements Action { public readonly type = UserPermissionsActionType.SET_PROJECTS_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class SetCollectionsPermissions implements Action { public readonly type = UserPermissionsActionType.SET_COLLECTIONS_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class SetLinkTypesPermissions implements Action { public readonly type = UserPermissionsActionType.SET_LINK_TYPES_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class SetViewsPermissions implements Action { public readonly type = UserPermissionsActionType.SET_VIEWS_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class
implements Action { public readonly type = UserPermissionsActionType.CLEAR; } export type All = | SetOrganizationPermissions | SetOrganizationsPermissions | SetProjectPermissions | SetProjectsPermissions | SetCollectionsPermissions | SetLinkTypesPermissions | SetViewsPermissions | Clear; }
Clear
identifier_name
error.rs
use wasm_core::value::Value; #[allow(dead_code)] #[repr(i32)] #[derive(Debug, Copy, Clone)] pub enum ErrorCode { Success = 0, Generic = 1, Eof = 2, Shutdown = 3, PermissionDenied = 4, OngoingIo = 5, InvalidInput = 6, BindFail = 7, NotFound = 8 } impl ErrorCode { pub fn to_ret(&self) -> Value { Value::I32(self.to_i32()) } pub fn
(&self) -> i32 { -(*self as i32) } } impl From<::std::io::ErrorKind> for ErrorCode { fn from(other: ::std::io::ErrorKind) -> ErrorCode { use std::io::ErrorKind::*; match other { NotFound => ErrorCode::NotFound, PermissionDenied => ErrorCode::PermissionDenied, InvalidInput => ErrorCode::InvalidInput, _ => ErrorCode::Generic } } }
to_i32
identifier_name
error.rs
use wasm_core::value::Value; #[allow(dead_code)] #[repr(i32)] #[derive(Debug, Copy, Clone)] pub enum ErrorCode { Success = 0, Generic = 1, Eof = 2, Shutdown = 3, PermissionDenied = 4, OngoingIo = 5, InvalidInput = 6, BindFail = 7, NotFound = 8 } impl ErrorCode { pub fn to_ret(&self) -> Value
pub fn to_i32(&self) -> i32 { -(*self as i32) } } impl From<::std::io::ErrorKind> for ErrorCode { fn from(other: ::std::io::ErrorKind) -> ErrorCode { use std::io::ErrorKind::*; match other { NotFound => ErrorCode::NotFound, PermissionDenied => ErrorCode::PermissionDenied, InvalidInput => ErrorCode::InvalidInput, _ => ErrorCode::Generic } } }
{ Value::I32(self.to_i32()) }
identifier_body
error.rs
use wasm_core::value::Value; #[allow(dead_code)] #[repr(i32)] #[derive(Debug, Copy, Clone)] pub enum ErrorCode {
Success = 0, Generic = 1, Eof = 2, Shutdown = 3, PermissionDenied = 4, OngoingIo = 5, InvalidInput = 6, BindFail = 7, NotFound = 8 } impl ErrorCode { pub fn to_ret(&self) -> Value { Value::I32(self.to_i32()) } pub fn to_i32(&self) -> i32 { -(*self as i32) } } impl From<::std::io::ErrorKind> for ErrorCode { fn from(other: ::std::io::ErrorKind) -> ErrorCode { use std::io::ErrorKind::*; match other { NotFound => ErrorCode::NotFound, PermissionDenied => ErrorCode::PermissionDenied, InvalidInput => ErrorCode::InvalidInput, _ => ErrorCode::Generic } } }
random_line_split
utilities.ts
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /// <reference path="./definitions/Q.d.ts" /> import Q = require('q'); import ctxm = require('./context'); import fs = require('fs'); var shell = require('shelljs'); var path = require('path'); // TODO: offer these module level context-less helper functions in utilities below export function ensurePathExists(path: string): Q.Promise<void> { var defer = Q.defer<void>(); if (fs.exists(path, (exists) => { if (!exists) { shell.mkdir('-p', path); var errMsg = shell.error(); if (errMsg) { defer.reject(new Error('Could not create path (' + path + '): ' + errMsg)); } else { defer.resolve(null); } } else { defer.resolve(null); } })); return defer.promise; } export function readFileContents(filePath: string, encoding: string) : Q.Promise<string> { var defer = Q.defer<string>(); fs.readFile(filePath, encoding, (err, data) => { if(err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { defer.resolve(data); } }); return defer.promise; } export function objectToFile(filePath: string, obj: any): Q.Promise<void> { var defer = Q.defer<void>(); fs.writeFile(filePath, JSON.stringify(obj, null, 2), (err) => { if (err) { defer.reject(new Error('Could not save to file (' + filePath + '): ' + err.message)); } else { defer.resolve(null); } }); return defer.promise; } export function objectFromFile(filePath: string): Q.Promise<any> { var defer = Q.defer<any>(); fs.readFile(filePath, (err, contents) => { if (err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { var obj: any = JSON.parse(contents.toString()); defer.resolve(obj); } }); return defer.promise; } // ret is { output: string, code: number } export function exec(cmdLine: string): Q.Promise<any> { var defer = Q.defer<any>(); shell.exec(cmdLine, (code, output) => { defer.resolve({code: code, output: output});
return defer.promise; } export function readDirectory(directory: string, includeFiles: boolean, includeFolders: boolean): Q.Promise<string[]> { var results: string[] = []; var deferred = Q.defer<string[]>(); if (includeFolders) { results.push(directory); } Q.nfcall(fs.readdir, directory) .then((files: string[]) => { var count = files.length; if (count > 0) { files.forEach((file: string, index: number) => { var fullPath = path.join(directory, file); Q.nfcall(fs.stat, fullPath) .then((stat: fs.Stats) => { if (stat && stat.isDirectory()) { readDirectory(fullPath, includeFiles, includeFolders) .then((moreFiles: string[]) => { results = results.concat(moreFiles); if (--count === 0) { deferred.resolve(results); } }, (error) => { deferred.reject(new Error(error.toString())); }); } else { if (includeFiles) { results.push(fullPath); } if (--count === 0) { deferred.resolve(results); } } }); }); } else { deferred.resolve(results); } }, (error) => { deferred.reject(error); }); return deferred.promise; } // // Utilities passed to each task // which provides contextual logging to server etc... // also contains general utility methods that would be useful to all task authors // export class Utilities { constructor(context: ctxm.Context) { this.ctx = context; } private ctx: ctxm.Context; // // '-a -b "quoted b value" -c -d "quoted d value"' becomes // [ '-a', '-b', '"quoted b value"', '-c', '-d', '"quoted d value"' ] // public argStringToArray(argString: string): string[] { var args = argString.match(/([^" ]*("[^"]*")[^" ]*)|[^" ]+/g); //remove double quotes from each string in args as child_process.spawn() cannot handle literla quotes as part of arguments for (var i = 0; i < args.length; i++) { args[i] = args[i].replace(/"/g, ""); } return args; } // spawn a process with stdout/err piped to context's logger // callback(err) public spawn(name: string, args: string[], options, callback: (err: any, returnCode: number) => void) { var failed = false; options = options || {}; args = args || []; var ops = { cwd: process.cwd(), env: process.env, failOnStdErr: true, failOnNonZeroRC: true }; // write over specified options over default options (ops) for (var op in options) { ops[op] = options[op]; } this.ctx.verbose('cwd: ' + ops.cwd); this.ctx.verbose('args: ' + args.toString()); this.ctx.info('running: ' + name + ' ' + args.join(' ')); var cp = require('child_process').spawn; var runCP = cp(name, args, ops); runCP.stdout.on('data', (data) => { this.ctx.info(data.toString('utf8')); }); runCP.stderr.on('data', (data) => { failed = ops.failOnStdErr; if (ops.failOnStdErr) { this.ctx.error(data.toString('utf8')); } else { this.ctx.info(data.toString('utf8')); } }); runCP.on('exit', (code) => { if (failed) { callback(new Error('Failed with Error Output'), code); return; } if (code == 0 || !ops.failOnNonZeroRC) { callback(null, code); } else { var msg = path.basename(name) + ' returned code: ' + code; callback(new Error(msg), code); } }); } }
});
random_line_split
utilities.ts
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /// <reference path="./definitions/Q.d.ts" /> import Q = require('q'); import ctxm = require('./context'); import fs = require('fs'); var shell = require('shelljs'); var path = require('path'); // TODO: offer these module level context-less helper functions in utilities below export function ensurePathExists(path: string): Q.Promise<void>
export function readFileContents(filePath: string, encoding: string) : Q.Promise<string> { var defer = Q.defer<string>(); fs.readFile(filePath, encoding, (err, data) => { if(err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { defer.resolve(data); } }); return defer.promise; } export function objectToFile(filePath: string, obj: any): Q.Promise<void> { var defer = Q.defer<void>(); fs.writeFile(filePath, JSON.stringify(obj, null, 2), (err) => { if (err) { defer.reject(new Error('Could not save to file (' + filePath + '): ' + err.message)); } else { defer.resolve(null); } }); return defer.promise; } export function objectFromFile(filePath: string): Q.Promise<any> { var defer = Q.defer<any>(); fs.readFile(filePath, (err, contents) => { if (err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { var obj: any = JSON.parse(contents.toString()); defer.resolve(obj); } }); return defer.promise; } // ret is { output: string, code: number } export function exec(cmdLine: string): Q.Promise<any> { var defer = Q.defer<any>(); shell.exec(cmdLine, (code, output) => { defer.resolve({code: code, output: output}); }); return defer.promise; } export function readDirectory(directory: string, includeFiles: boolean, includeFolders: boolean): Q.Promise<string[]> { var results: string[] = []; var deferred = Q.defer<string[]>(); if (includeFolders) { results.push(directory); } Q.nfcall(fs.readdir, directory) .then((files: string[]) => { var count = files.length; if (count > 0) { files.forEach((file: string, index: number) => { var fullPath = path.join(directory, file); Q.nfcall(fs.stat, fullPath) .then((stat: fs.Stats) => { if (stat && stat.isDirectory()) { readDirectory(fullPath, includeFiles, includeFolders) .then((moreFiles: string[]) => { results = results.concat(moreFiles); if (--count === 0) { deferred.resolve(results); } }, (error) => { deferred.reject(new Error(error.toString())); }); } else { if (includeFiles) { results.push(fullPath); } if (--count === 0) { deferred.resolve(results); } } }); }); } else { deferred.resolve(results); } }, (error) => { deferred.reject(error); }); return deferred.promise; } // // Utilities passed to each task // which provides contextual logging to server etc... // also contains general utility methods that would be useful to all task authors // export class Utilities { constructor(context: ctxm.Context) { this.ctx = context; } private ctx: ctxm.Context; // // '-a -b "quoted b value" -c -d "quoted d value"' becomes // [ '-a', '-b', '"quoted b value"', '-c', '-d', '"quoted d value"' ] // public argStringToArray(argString: string): string[] { var args = argString.match(/([^" ]*("[^"]*")[^" ]*)|[^" ]+/g); //remove double quotes from each string in args as child_process.spawn() cannot handle literla quotes as part of arguments for (var i = 0; i < args.length; i++) { args[i] = args[i].replace(/"/g, ""); } return args; } // spawn a process with stdout/err piped to context's logger // callback(err) public spawn(name: string, args: string[], options, callback: (err: any, returnCode: number) => void) { var failed = false; options = options || {}; args = args || []; var ops = { cwd: process.cwd(), env: process.env, failOnStdErr: true, failOnNonZeroRC: true }; // write over specified options over default options (ops) for (var op in options) { ops[op] = options[op]; } this.ctx.verbose('cwd: ' + ops.cwd); this.ctx.verbose('args: ' + args.toString()); this.ctx.info('running: ' + name + ' ' + args.join(' ')); var cp = require('child_process').spawn; var runCP = cp(name, args, ops); runCP.stdout.on('data', (data) => { this.ctx.info(data.toString('utf8')); }); runCP.stderr.on('data', (data) => { failed = ops.failOnStdErr; if (ops.failOnStdErr) { this.ctx.error(data.toString('utf8')); } else { this.ctx.info(data.toString('utf8')); } }); runCP.on('exit', (code) => { if (failed) { callback(new Error('Failed with Error Output'), code); return; } if (code == 0 || !ops.failOnNonZeroRC) { callback(null, code); } else { var msg = path.basename(name) + ' returned code: ' + code; callback(new Error(msg), code); } }); } }
{ var defer = Q.defer<void>(); if (fs.exists(path, (exists) => { if (!exists) { shell.mkdir('-p', path); var errMsg = shell.error(); if (errMsg) { defer.reject(new Error('Could not create path (' + path + '): ' + errMsg)); } else { defer.resolve(null); } } else { defer.resolve(null); } })); return defer.promise; }
identifier_body
utilities.ts
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /// <reference path="./definitions/Q.d.ts" /> import Q = require('q'); import ctxm = require('./context'); import fs = require('fs'); var shell = require('shelljs'); var path = require('path'); // TODO: offer these module level context-less helper functions in utilities below export function ensurePathExists(path: string): Q.Promise<void> { var defer = Q.defer<void>(); if (fs.exists(path, (exists) => { if (!exists) { shell.mkdir('-p', path); var errMsg = shell.error(); if (errMsg) { defer.reject(new Error('Could not create path (' + path + '): ' + errMsg)); } else
} else { defer.resolve(null); } })); return defer.promise; } export function readFileContents(filePath: string, encoding: string) : Q.Promise<string> { var defer = Q.defer<string>(); fs.readFile(filePath, encoding, (err, data) => { if(err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { defer.resolve(data); } }); return defer.promise; } export function objectToFile(filePath: string, obj: any): Q.Promise<void> { var defer = Q.defer<void>(); fs.writeFile(filePath, JSON.stringify(obj, null, 2), (err) => { if (err) { defer.reject(new Error('Could not save to file (' + filePath + '): ' + err.message)); } else { defer.resolve(null); } }); return defer.promise; } export function objectFromFile(filePath: string): Q.Promise<any> { var defer = Q.defer<any>(); fs.readFile(filePath, (err, contents) => { if (err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { var obj: any = JSON.parse(contents.toString()); defer.resolve(obj); } }); return defer.promise; } // ret is { output: string, code: number } export function exec(cmdLine: string): Q.Promise<any> { var defer = Q.defer<any>(); shell.exec(cmdLine, (code, output) => { defer.resolve({code: code, output: output}); }); return defer.promise; } export function readDirectory(directory: string, includeFiles: boolean, includeFolders: boolean): Q.Promise<string[]> { var results: string[] = []; var deferred = Q.defer<string[]>(); if (includeFolders) { results.push(directory); } Q.nfcall(fs.readdir, directory) .then((files: string[]) => { var count = files.length; if (count > 0) { files.forEach((file: string, index: number) => { var fullPath = path.join(directory, file); Q.nfcall(fs.stat, fullPath) .then((stat: fs.Stats) => { if (stat && stat.isDirectory()) { readDirectory(fullPath, includeFiles, includeFolders) .then((moreFiles: string[]) => { results = results.concat(moreFiles); if (--count === 0) { deferred.resolve(results); } }, (error) => { deferred.reject(new Error(error.toString())); }); } else { if (includeFiles) { results.push(fullPath); } if (--count === 0) { deferred.resolve(results); } } }); }); } else { deferred.resolve(results); } }, (error) => { deferred.reject(error); }); return deferred.promise; } // // Utilities passed to each task // which provides contextual logging to server etc... // also contains general utility methods that would be useful to all task authors // export class Utilities { constructor(context: ctxm.Context) { this.ctx = context; } private ctx: ctxm.Context; // // '-a -b "quoted b value" -c -d "quoted d value"' becomes // [ '-a', '-b', '"quoted b value"', '-c', '-d', '"quoted d value"' ] // public argStringToArray(argString: string): string[] { var args = argString.match(/([^" ]*("[^"]*")[^" ]*)|[^" ]+/g); //remove double quotes from each string in args as child_process.spawn() cannot handle literla quotes as part of arguments for (var i = 0; i < args.length; i++) { args[i] = args[i].replace(/"/g, ""); } return args; } // spawn a process with stdout/err piped to context's logger // callback(err) public spawn(name: string, args: string[], options, callback: (err: any, returnCode: number) => void) { var failed = false; options = options || {}; args = args || []; var ops = { cwd: process.cwd(), env: process.env, failOnStdErr: true, failOnNonZeroRC: true }; // write over specified options over default options (ops) for (var op in options) { ops[op] = options[op]; } this.ctx.verbose('cwd: ' + ops.cwd); this.ctx.verbose('args: ' + args.toString()); this.ctx.info('running: ' + name + ' ' + args.join(' ')); var cp = require('child_process').spawn; var runCP = cp(name, args, ops); runCP.stdout.on('data', (data) => { this.ctx.info(data.toString('utf8')); }); runCP.stderr.on('data', (data) => { failed = ops.failOnStdErr; if (ops.failOnStdErr) { this.ctx.error(data.toString('utf8')); } else { this.ctx.info(data.toString('utf8')); } }); runCP.on('exit', (code) => { if (failed) { callback(new Error('Failed with Error Output'), code); return; } if (code == 0 || !ops.failOnNonZeroRC) { callback(null, code); } else { var msg = path.basename(name) + ' returned code: ' + code; callback(new Error(msg), code); } }); } }
{ defer.resolve(null); }
conditional_block
utilities.ts
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /// <reference path="./definitions/Q.d.ts" /> import Q = require('q'); import ctxm = require('./context'); import fs = require('fs'); var shell = require('shelljs'); var path = require('path'); // TODO: offer these module level context-less helper functions in utilities below export function ensurePathExists(path: string): Q.Promise<void> { var defer = Q.defer<void>(); if (fs.exists(path, (exists) => { if (!exists) { shell.mkdir('-p', path); var errMsg = shell.error(); if (errMsg) { defer.reject(new Error('Could not create path (' + path + '): ' + errMsg)); } else { defer.resolve(null); } } else { defer.resolve(null); } })); return defer.promise; } export function readFileContents(filePath: string, encoding: string) : Q.Promise<string> { var defer = Q.defer<string>(); fs.readFile(filePath, encoding, (err, data) => { if(err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { defer.resolve(data); } }); return defer.promise; } export function objectToFile(filePath: string, obj: any): Q.Promise<void> { var defer = Q.defer<void>(); fs.writeFile(filePath, JSON.stringify(obj, null, 2), (err) => { if (err) { defer.reject(new Error('Could not save to file (' + filePath + '): ' + err.message)); } else { defer.resolve(null); } }); return defer.promise; } export function objectFromFile(filePath: string): Q.Promise<any> { var defer = Q.defer<any>(); fs.readFile(filePath, (err, contents) => { if (err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { var obj: any = JSON.parse(contents.toString()); defer.resolve(obj); } }); return defer.promise; } // ret is { output: string, code: number } export function exec(cmdLine: string): Q.Promise<any> { var defer = Q.defer<any>(); shell.exec(cmdLine, (code, output) => { defer.resolve({code: code, output: output}); }); return defer.promise; } export function readDirectory(directory: string, includeFiles: boolean, includeFolders: boolean): Q.Promise<string[]> { var results: string[] = []; var deferred = Q.defer<string[]>(); if (includeFolders) { results.push(directory); } Q.nfcall(fs.readdir, directory) .then((files: string[]) => { var count = files.length; if (count > 0) { files.forEach((file: string, index: number) => { var fullPath = path.join(directory, file); Q.nfcall(fs.stat, fullPath) .then((stat: fs.Stats) => { if (stat && stat.isDirectory()) { readDirectory(fullPath, includeFiles, includeFolders) .then((moreFiles: string[]) => { results = results.concat(moreFiles); if (--count === 0) { deferred.resolve(results); } }, (error) => { deferred.reject(new Error(error.toString())); }); } else { if (includeFiles) { results.push(fullPath); } if (--count === 0) { deferred.resolve(results); } } }); }); } else { deferred.resolve(results); } }, (error) => { deferred.reject(error); }); return deferred.promise; } // // Utilities passed to each task // which provides contextual logging to server etc... // also contains general utility methods that would be useful to all task authors // export class
{ constructor(context: ctxm.Context) { this.ctx = context; } private ctx: ctxm.Context; // // '-a -b "quoted b value" -c -d "quoted d value"' becomes // [ '-a', '-b', '"quoted b value"', '-c', '-d', '"quoted d value"' ] // public argStringToArray(argString: string): string[] { var args = argString.match(/([^" ]*("[^"]*")[^" ]*)|[^" ]+/g); //remove double quotes from each string in args as child_process.spawn() cannot handle literla quotes as part of arguments for (var i = 0; i < args.length; i++) { args[i] = args[i].replace(/"/g, ""); } return args; } // spawn a process with stdout/err piped to context's logger // callback(err) public spawn(name: string, args: string[], options, callback: (err: any, returnCode: number) => void) { var failed = false; options = options || {}; args = args || []; var ops = { cwd: process.cwd(), env: process.env, failOnStdErr: true, failOnNonZeroRC: true }; // write over specified options over default options (ops) for (var op in options) { ops[op] = options[op]; } this.ctx.verbose('cwd: ' + ops.cwd); this.ctx.verbose('args: ' + args.toString()); this.ctx.info('running: ' + name + ' ' + args.join(' ')); var cp = require('child_process').spawn; var runCP = cp(name, args, ops); runCP.stdout.on('data', (data) => { this.ctx.info(data.toString('utf8')); }); runCP.stderr.on('data', (data) => { failed = ops.failOnStdErr; if (ops.failOnStdErr) { this.ctx.error(data.toString('utf8')); } else { this.ctx.info(data.toString('utf8')); } }); runCP.on('exit', (code) => { if (failed) { callback(new Error('Failed with Error Output'), code); return; } if (code == 0 || !ops.failOnNonZeroRC) { callback(null, code); } else { var msg = path.basename(name) + ' returned code: ' + code; callback(new Error(msg), code); } }); } }
Utilities
identifier_name
formatting.ts
// // Copyright (c) Microsoft Corporation. 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. // ///<reference path='..\typescriptServices.ts' />
///<reference path='formattingManager.ts' /> ///<reference path='formattingRequestKind.ts' /> ///<reference path='rule.ts' /> ///<reference path='ruleAction.ts' /> ///<reference path='ruleDescriptor.ts' /> ///<reference path='ruleFlag.ts' /> ///<reference path='ruleOperation.ts' /> ///<reference path='ruleOperationContext.ts' /> ///<reference path='rules.ts' /> ///<reference path='rulesMap.ts' /> ///<reference path='rulesProvider.ts' /> ///<reference path='textEditInfo.ts' /> ///<reference path='tokenRange.ts' /> ///<reference path='tokenSpan.ts' /> ///<reference path='indentationNodeContext.ts' /> ///<reference path='indentationNodeContextPool.ts' /> ///<reference path='indentationTrackingWalker.ts' /> ///<reference path='multipleTokenIndenter.ts' /> ///<reference path='singleTokenIndenter.ts' /> ///<reference path='formatter.ts' />
///<reference path='textSnapshot.ts' /> ///<reference path='textSnapshotLine.ts' /> ///<reference path='snapshotPoint.ts' /> ///<reference path='formattingContext.ts' />
random_line_split
RecentHistory-test.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { get, remove, save } from '../../../helpers/storage'; import RecentHistory, { History } from '../RecentHistory'; jest.mock('../../../helpers/storage', () => ({ get: jest.fn(), remove: jest.fn(), save: jest.fn() })); beforeEach(() => {
(save as jest.Mock).mockClear(); }); it('should get existing history', () => { const history = [{ key: 'foo', name: 'Foo', icon: 'TRK' }]; (get as jest.Mock).mockReturnValueOnce(JSON.stringify(history)); expect(RecentHistory.get()).toEqual(history); expect(get).toBeCalledWith('sonar_recent_history'); }); it('should get empty history', () => { (get as jest.Mock).mockReturnValueOnce(null); expect(RecentHistory.get()).toEqual([]); expect(get).toBeCalledWith('sonar_recent_history'); }); it('should return [] and clear history in case of failure', () => { (get as jest.Mock).mockReturnValueOnce('not a json'); expect(RecentHistory.get()).toEqual([]); expect(get).toBeCalledWith('sonar_recent_history'); expect(remove).toBeCalledWith('sonar_recent_history'); }); it('should save history', () => { const history = [{ key: 'foo', name: 'Foo', icon: 'TRK' }]; RecentHistory.set(history); expect(save).toBeCalledWith('sonar_recent_history', JSON.stringify(history)); }); it('should clear history', () => { RecentHistory.clear(); expect(remove).toBeCalledWith('sonar_recent_history'); }); it('should add item to history', () => { const history = [{ key: 'foo', name: 'Foo', icon: 'TRK' }]; (get as jest.Mock).mockReturnValueOnce(JSON.stringify(history)); RecentHistory.add('bar', 'Bar', 'VW'); expect(save).toBeCalledWith( 'sonar_recent_history', JSON.stringify([{ key: 'bar', name: 'Bar', icon: 'VW' }, ...history]) ); }); it('should keep 10 items maximum', () => { const history: History = []; for (let i = 0; i < 10; i++) { history.push({ key: `key-${i}`, name: `name-${i}`, icon: 'TRK' }); } (get as jest.Mock).mockReturnValueOnce(JSON.stringify(history)); RecentHistory.add('bar', 'Bar', 'VW'); expect(save).toBeCalledWith( 'sonar_recent_history', JSON.stringify([{ key: 'bar', name: 'Bar', icon: 'VW' }, ...history.slice(0, 9)]) ); }); it('should remove component from history', () => { const history: History = []; for (let i = 0; i < 10; i++) { history.push({ key: `key-${i}`, name: `name-${i}`, icon: 'TRK' }); } (get as jest.Mock).mockReturnValueOnce(JSON.stringify(history)); RecentHistory.remove('key-5'); expect(save).toBeCalledWith( 'sonar_recent_history', JSON.stringify([...history.slice(0, 5), ...history.slice(6)]) ); });
(get as jest.Mock).mockClear(); (remove as jest.Mock).mockClear();
random_line_split
RecentHistory-test.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { get, remove, save } from '../../../helpers/storage'; import RecentHistory, { History } from '../RecentHistory'; jest.mock('../../../helpers/storage', () => ({ get: jest.fn(), remove: jest.fn(), save: jest.fn() })); beforeEach(() => { (get as jest.Mock).mockClear(); (remove as jest.Mock).mockClear(); (save as jest.Mock).mockClear(); }); it('should get existing history', () => { const history = [{ key: 'foo', name: 'Foo', icon: 'TRK' }]; (get as jest.Mock).mockReturnValueOnce(JSON.stringify(history)); expect(RecentHistory.get()).toEqual(history); expect(get).toBeCalledWith('sonar_recent_history'); }); it('should get empty history', () => { (get as jest.Mock).mockReturnValueOnce(null); expect(RecentHistory.get()).toEqual([]); expect(get).toBeCalledWith('sonar_recent_history'); }); it('should return [] and clear history in case of failure', () => { (get as jest.Mock).mockReturnValueOnce('not a json'); expect(RecentHistory.get()).toEqual([]); expect(get).toBeCalledWith('sonar_recent_history'); expect(remove).toBeCalledWith('sonar_recent_history'); }); it('should save history', () => { const history = [{ key: 'foo', name: 'Foo', icon: 'TRK' }]; RecentHistory.set(history); expect(save).toBeCalledWith('sonar_recent_history', JSON.stringify(history)); }); it('should clear history', () => { RecentHistory.clear(); expect(remove).toBeCalledWith('sonar_recent_history'); }); it('should add item to history', () => { const history = [{ key: 'foo', name: 'Foo', icon: 'TRK' }]; (get as jest.Mock).mockReturnValueOnce(JSON.stringify(history)); RecentHistory.add('bar', 'Bar', 'VW'); expect(save).toBeCalledWith( 'sonar_recent_history', JSON.stringify([{ key: 'bar', name: 'Bar', icon: 'VW' }, ...history]) ); }); it('should keep 10 items maximum', () => { const history: History = []; for (let i = 0; i < 10; i++) { history.push({ key: `key-${i}`, name: `name-${i}`, icon: 'TRK' }); } (get as jest.Mock).mockReturnValueOnce(JSON.stringify(history)); RecentHistory.add('bar', 'Bar', 'VW'); expect(save).toBeCalledWith( 'sonar_recent_history', JSON.stringify([{ key: 'bar', name: 'Bar', icon: 'VW' }, ...history.slice(0, 9)]) ); }); it('should remove component from history', () => { const history: History = []; for (let i = 0; i < 10; i++)
(get as jest.Mock).mockReturnValueOnce(JSON.stringify(history)); RecentHistory.remove('key-5'); expect(save).toBeCalledWith( 'sonar_recent_history', JSON.stringify([...history.slice(0, 5), ...history.slice(6)]) ); });
{ history.push({ key: `key-${i}`, name: `name-${i}`, icon: 'TRK' }); }
conditional_block
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str>
pub fn enumerate_devices(display: *mut xlib::Display) { let mut ndevices = 0; let devices_ptr = unsafe { xinput2::XIQueryDevice(display, xinput2::XIAllDevices, &mut ndevices) }; let xi_devices = unsafe { slice::from_raw_parts(devices_ptr, ndevices as usize) }; let dev_use = ["unk", "XIMasterPointer", "XIMasterKeyboard", "XISlavePointer", "XISlaveKeyboard", "XIFloatingSlave"]; let dev_class = ["XIKeyClass", "XIButtonClass", "XIValuatorClass", "XIScrollClass", "4", "5", "6", "7", "XITouchClass"]; for dev in xi_devices { let name = unsafe{ CStr::from_ptr(dev.name) }; println!("-- device {} {:?} is a {} (paired with {})", dev.deviceid, name, dev_use[dev._use as usize], dev.attachment); for i in 0 .. dev.num_classes as isize { let class = unsafe { *dev.classes.offset(i) }; let _type = unsafe { (*class)._type }; let ci_str = match _type { xinput2::XIKeyClass => { let key_c: &xinput2::XIKeyClassInfo = unsafe { mem::transmute(class) }; format!("{} keycodes", key_c.num_keycodes) } xinput2::XIButtonClass => { let but_c: &xinput2::XIButtonClassInfo = unsafe { mem::transmute(class) }; let atoms = unsafe { slice::from_raw_parts(but_c.labels, but_c.num_buttons as usize) }; let buttons: Vec<(_, _)> = atoms.iter().map(|&atom| { if atom != 0 { unsafe { let ptr = xlib::XGetAtomName(display, atom); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() } }).enumerate().map(|(i, s)| (i+1, s)).collect(); format!("{} buttons {:?}", but_c.num_buttons, buttons) }, xinput2::XIValuatorClass => { let val_c: &xinput2::XIValuatorClassInfo = unsafe { mem::transmute(class) }; let name = if val_c.label != 0 { unsafe { let ptr = xlib::XGetAtomName(display, val_c.label); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() }; format!("number {}, name {:?}, min {}, max {}, res {}, mode {}", val_c.number, name, val_c.min, val_c.max, val_c.resolution, val_c.mode) }, xinput2::XIScrollClass => { let scr_c: &xinput2::XIScrollClassInfo = unsafe { mem::transmute(class) }; format!("number {}, stype {}, incr {}, flags={}", scr_c.number, scr_c.scroll_type, scr_c.increment, scr_c.flags) }, xinput2::XITouchClass => { let tou_c: &xinput2::XITouchClassInfo = unsafe { mem::transmute(class) }; format!("mode {}, num_touches {}", tou_c.mode, tou_c.num_touches) }, _ => unreachable!() }; println!(" class: {} ({})", dev_class[_type as usize], ci_str); } } unsafe{ xinput2::XIFreeDeviceInfo(devices_ptr); } println!("---"); }
{ (0 .. desc.len()).filter(|i| flags & (1 << i) != 0).map(|i| desc[i]).collect() }
identifier_body
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str> { (0 .. desc.len()).filter(|i| flags & (1 << i) != 0).map(|i| desc[i]).collect() } pub fn
(display: *mut xlib::Display) { let mut ndevices = 0; let devices_ptr = unsafe { xinput2::XIQueryDevice(display, xinput2::XIAllDevices, &mut ndevices) }; let xi_devices = unsafe { slice::from_raw_parts(devices_ptr, ndevices as usize) }; let dev_use = ["unk", "XIMasterPointer", "XIMasterKeyboard", "XISlavePointer", "XISlaveKeyboard", "XIFloatingSlave"]; let dev_class = ["XIKeyClass", "XIButtonClass", "XIValuatorClass", "XIScrollClass", "4", "5", "6", "7", "XITouchClass"]; for dev in xi_devices { let name = unsafe{ CStr::from_ptr(dev.name) }; println!("-- device {} {:?} is a {} (paired with {})", dev.deviceid, name, dev_use[dev._use as usize], dev.attachment); for i in 0 .. dev.num_classes as isize { let class = unsafe { *dev.classes.offset(i) }; let _type = unsafe { (*class)._type }; let ci_str = match _type { xinput2::XIKeyClass => { let key_c: &xinput2::XIKeyClassInfo = unsafe { mem::transmute(class) }; format!("{} keycodes", key_c.num_keycodes) } xinput2::XIButtonClass => { let but_c: &xinput2::XIButtonClassInfo = unsafe { mem::transmute(class) }; let atoms = unsafe { slice::from_raw_parts(but_c.labels, but_c.num_buttons as usize) }; let buttons: Vec<(_, _)> = atoms.iter().map(|&atom| { if atom != 0 { unsafe { let ptr = xlib::XGetAtomName(display, atom); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() } }).enumerate().map(|(i, s)| (i+1, s)).collect(); format!("{} buttons {:?}", but_c.num_buttons, buttons) }, xinput2::XIValuatorClass => { let val_c: &xinput2::XIValuatorClassInfo = unsafe { mem::transmute(class) }; let name = if val_c.label != 0 { unsafe { let ptr = xlib::XGetAtomName(display, val_c.label); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() }; format!("number {}, name {:?}, min {}, max {}, res {}, mode {}", val_c.number, name, val_c.min, val_c.max, val_c.resolution, val_c.mode) }, xinput2::XIScrollClass => { let scr_c: &xinput2::XIScrollClassInfo = unsafe { mem::transmute(class) }; format!("number {}, stype {}, incr {}, flags={}", scr_c.number, scr_c.scroll_type, scr_c.increment, scr_c.flags) }, xinput2::XITouchClass => { let tou_c: &xinput2::XITouchClassInfo = unsafe { mem::transmute(class) }; format!("mode {}, num_touches {}", tou_c.mode, tou_c.num_touches) }, _ => unreachable!() }; println!(" class: {} ({})", dev_class[_type as usize], ci_str); } } unsafe{ xinput2::XIFreeDeviceInfo(devices_ptr); } println!("---"); }
enumerate_devices
identifier_name
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str> { (0 .. desc.len()).filter(|i| flags & (1 << i) != 0).map(|i| desc[i]).collect() } pub fn enumerate_devices(display: *mut xlib::Display) { let mut ndevices = 0; let devices_ptr = unsafe { xinput2::XIQueryDevice(display, xinput2::XIAllDevices, &mut ndevices) }; let xi_devices = unsafe { slice::from_raw_parts(devices_ptr, ndevices as usize) }; let dev_use = ["unk", "XIMasterPointer", "XIMasterKeyboard", "XISlavePointer", "XISlaveKeyboard", "XIFloatingSlave"];
println!("-- device {} {:?} is a {} (paired with {})", dev.deviceid, name, dev_use[dev._use as usize], dev.attachment); for i in 0 .. dev.num_classes as isize { let class = unsafe { *dev.classes.offset(i) }; let _type = unsafe { (*class)._type }; let ci_str = match _type { xinput2::XIKeyClass => { let key_c: &xinput2::XIKeyClassInfo = unsafe { mem::transmute(class) }; format!("{} keycodes", key_c.num_keycodes) } xinput2::XIButtonClass => { let but_c: &xinput2::XIButtonClassInfo = unsafe { mem::transmute(class) }; let atoms = unsafe { slice::from_raw_parts(but_c.labels, but_c.num_buttons as usize) }; let buttons: Vec<(_, _)> = atoms.iter().map(|&atom| { if atom != 0 { unsafe { let ptr = xlib::XGetAtomName(display, atom); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() } }).enumerate().map(|(i, s)| (i+1, s)).collect(); format!("{} buttons {:?}", but_c.num_buttons, buttons) }, xinput2::XIValuatorClass => { let val_c: &xinput2::XIValuatorClassInfo = unsafe { mem::transmute(class) }; let name = if val_c.label != 0 { unsafe { let ptr = xlib::XGetAtomName(display, val_c.label); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() }; format!("number {}, name {:?}, min {}, max {}, res {}, mode {}", val_c.number, name, val_c.min, val_c.max, val_c.resolution, val_c.mode) }, xinput2::XIScrollClass => { let scr_c: &xinput2::XIScrollClassInfo = unsafe { mem::transmute(class) }; format!("number {}, stype {}, incr {}, flags={}", scr_c.number, scr_c.scroll_type, scr_c.increment, scr_c.flags) }, xinput2::XITouchClass => { let tou_c: &xinput2::XITouchClassInfo = unsafe { mem::transmute(class) }; format!("mode {}, num_touches {}", tou_c.mode, tou_c.num_touches) }, _ => unreachable!() }; println!(" class: {} ({})", dev_class[_type as usize], ci_str); } } unsafe{ xinput2::XIFreeDeviceInfo(devices_ptr); } println!("---"); }
let dev_class = ["XIKeyClass", "XIButtonClass", "XIValuatorClass", "XIScrollClass", "4", "5", "6", "7", "XITouchClass"]; for dev in xi_devices { let name = unsafe{ CStr::from_ptr(dev.name) };
random_line_split
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str> { (0 .. desc.len()).filter(|i| flags & (1 << i) != 0).map(|i| desc[i]).collect() } pub fn enumerate_devices(display: *mut xlib::Display) { let mut ndevices = 0; let devices_ptr = unsafe { xinput2::XIQueryDevice(display, xinput2::XIAllDevices, &mut ndevices) }; let xi_devices = unsafe { slice::from_raw_parts(devices_ptr, ndevices as usize) }; let dev_use = ["unk", "XIMasterPointer", "XIMasterKeyboard", "XISlavePointer", "XISlaveKeyboard", "XIFloatingSlave"]; let dev_class = ["XIKeyClass", "XIButtonClass", "XIValuatorClass", "XIScrollClass", "4", "5", "6", "7", "XITouchClass"]; for dev in xi_devices { let name = unsafe{ CStr::from_ptr(dev.name) }; println!("-- device {} {:?} is a {} (paired with {})", dev.deviceid, name, dev_use[dev._use as usize], dev.attachment); for i in 0 .. dev.num_classes as isize { let class = unsafe { *dev.classes.offset(i) }; let _type = unsafe { (*class)._type }; let ci_str = match _type { xinput2::XIKeyClass => { let key_c: &xinput2::XIKeyClassInfo = unsafe { mem::transmute(class) }; format!("{} keycodes", key_c.num_keycodes) } xinput2::XIButtonClass => { let but_c: &xinput2::XIButtonClassInfo = unsafe { mem::transmute(class) }; let atoms = unsafe { slice::from_raw_parts(but_c.labels, but_c.num_buttons as usize) }; let buttons: Vec<(_, _)> = atoms.iter().map(|&atom| { if atom != 0 { unsafe { let ptr = xlib::XGetAtomName(display, atom); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() } }).enumerate().map(|(i, s)| (i+1, s)).collect(); format!("{} buttons {:?}", but_c.num_buttons, buttons) }, xinput2::XIValuatorClass => { let val_c: &xinput2::XIValuatorClassInfo = unsafe { mem::transmute(class) }; let name = if val_c.label != 0
else { CString::new("(null)").unwrap() }; format!("number {}, name {:?}, min {}, max {}, res {}, mode {}", val_c.number, name, val_c.min, val_c.max, val_c.resolution, val_c.mode) }, xinput2::XIScrollClass => { let scr_c: &xinput2::XIScrollClassInfo = unsafe { mem::transmute(class) }; format!("number {}, stype {}, incr {}, flags={}", scr_c.number, scr_c.scroll_type, scr_c.increment, scr_c.flags) }, xinput2::XITouchClass => { let tou_c: &xinput2::XITouchClassInfo = unsafe { mem::transmute(class) }; format!("mode {}, num_touches {}", tou_c.mode, tou_c.num_touches) }, _ => unreachable!() }; println!(" class: {} ({})", dev_class[_type as usize], ci_str); } } unsafe{ xinput2::XIFreeDeviceInfo(devices_ptr); } println!("---"); }
{ unsafe { let ptr = xlib::XGetAtomName(display, val_c.label); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } }
conditional_block
dnsutils.py
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Endre Karlson <endre.karlson@hp.com> # # 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 random import socket import base64 import time from threading import Lock import six import dns import dns.exception import dns.zone import eventlet from dns import rdatatype from oslo_log import log as logging from oslo_config import cfg from designate import context from designate import exceptions from designate import objects from designate.i18n import _LE from designate.i18n import _LI LOG = logging.getLogger(__name__) util_opts = [ cfg.IntOpt('xfr_timeout', help="Timeout in seconds for XFR's.", default=10) ] class DNSMiddleware(object): """Base DNS Middleware class with some utility methods""" def __init__(self, application): self.application = application def process_request(self, request): """Called on each request. If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here. """ return None def process_response(self, response): """Do whatever you'd like to the response.""" return response def __call__(self, request): response = self.process_request(request) if response: return response response = self.application(request) return self.process_response(response) def _build_error_response(self): response = dns.message.make_response( dns.message.make_query('unknown', dns.rdatatype.A)) response.set_rcode(dns.rcode.FORMERR) return response class SerializationMiddleware(DNSMiddleware): """DNS Middleware to serialize/deserialize DNS Packets""" def __init__(self, application, tsig_keyring=None): self.application = application self.tsig_keyring = tsig_keyring def
(self, request): # Generate the initial context. This may be updated by other middleware # as we learn more information about the Request. ctxt = context.DesignateContext.get_admin_context(all_tenants=True) try: message = dns.message.from_wire(request['payload'], self.tsig_keyring) if message.had_tsig: LOG.debug('Request signed with TSIG key: %s', message.keyname) # Create + Attach the initial "environ" dict. This is similar to # the environ dict used in typical WSGI middleware. message.environ = { 'context': ctxt, 'addr': request['addr'], } except dns.message.UnknownTSIGKey: LOG.error(_LE("Unknown TSIG key from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except dns.tsig.BadSignature: LOG.error(_LE("Invalid TSIG signature from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except dns.exception.DNSException: LOG.error(_LE("Failed to deserialize packet from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except Exception: LOG.exception(_LE("Unknown exception deserializing packet " "from %(host)s %(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() else: # Hand the Deserialized packet onto the Application for response in self.application(message): # Serialize and return the response if present if isinstance(response, dns.message.Message): yield response.to_wire(max_size=65535) elif isinstance(response, dns.renderer.Renderer): yield response.get_wire() class TsigInfoMiddleware(DNSMiddleware): """Middleware which looks up the information available for a TsigKey""" def __init__(self, application, storage): super(TsigInfoMiddleware, self).__init__(application) self.storage = storage def process_request(self, request): if not request.had_tsig: return None try: criterion = {'name': request.keyname.to_text(True)} tsigkey = self.storage.find_tsigkey( context.get_current(), criterion) request.environ['tsigkey'] = tsigkey request.environ['context'].tsigkey_id = tsigkey.id except exceptions.TsigKeyNotFound: # This should never happen, as we just validated the key.. Except # for race conditions.. return self._build_error_response() return None class TsigKeyring(object): """Implements the DNSPython KeyRing API, backed by the Designate DB""" def __init__(self, storage): self.storage = storage def __getitem__(self, key): return self.get(key) def get(self, key, default=None): try: criterion = {'name': key.to_text(True)} tsigkey = self.storage.find_tsigkey( context.get_current(), criterion) return base64.decodestring(tsigkey.secret) except exceptions.TsigKeyNotFound: return default class ZoneLock(object): """A Lock across all zones that enforces a rate limit on NOTIFYs""" def __init__(self, delay): self.lock = Lock() self.data = {} self.delay = delay def acquire(self, zone): with self.lock: # If no one holds the lock for the zone, grant it if zone not in self.data: self.data[zone] = time.time() return True # Otherwise, get the time that it was locked locktime = self.data[zone] now = time.time() period = now - locktime # If it has been locked for longer than the allowed period # give the lock to the new requester if period > self.delay: self.data[zone] = now return True LOG.debug('Lock for %(zone)s can\'t be releaesed for %(period)s' 'seconds' % {'zone': zone, 'period': str(self.delay - period)}) # Don't grant the lock for the zone return False def release(self, zone): # Release the lock with self.lock: try: self.data.pop(zone) except KeyError: pass class LimitNotifyMiddleware(DNSMiddleware): """Middleware that rate limits NOTIFYs to the Agent""" def __init__(self, application): super(LimitNotifyMiddleware, self).__init__(application) self.delay = cfg.CONF['service:agent'].notify_delay self.locker = ZoneLock(self.delay) def process_request(self, request): opcode = request.opcode() if opcode != dns.opcode.NOTIFY: return None zone_name = request.question[0].name.to_text() if self.locker.acquire(zone_name): time.sleep(self.delay) self.locker.release(zone_name) return None else: LOG.debug('Threw away NOTIFY for %(zone)s, already ' 'working on an update.' % {'zone': zone_name}) response = dns.message.make_response(request) # Provide an authoritative answer response.flags |= dns.flags.AA return (response,) def from_dnspython_zone(dnspython_zone): # dnspython never builds a zone with more than one SOA, even if we give # it a zonefile that contains more than one soa = dnspython_zone.get_rdataset(dnspython_zone.origin, 'SOA') if soa is None: raise exceptions.BadRequest('An SOA record is required') email = soa[0].rname.to_text().rstrip('.') email = email.replace('.', '@', 1) values = { 'name': dnspython_zone.origin.to_text(), 'email': email, 'ttl': soa.ttl, 'serial': soa[0].serial, 'retry': soa[0].retry, 'expire': soa[0].expire } zone = objects.Domain(**values) rrsets = dnspyrecords_to_recordsetlist(dnspython_zone.nodes) zone.recordsets = rrsets return zone def dnspyrecords_to_recordsetlist(dnspython_records): rrsets = objects.RecordList() for rname in six.iterkeys(dnspython_records): for rdataset in dnspython_records[rname]: rrset = dnspythonrecord_to_recordset(rname, rdataset) if rrset is None: continue rrsets.append(rrset) return rrsets def dnspythonrecord_to_recordset(rname, rdataset): record_type = rdatatype.to_text(rdataset.rdtype) # Create the other recordsets values = { 'name': rname.to_text(), 'type': record_type } if rdataset.ttl != 0: values['ttl'] = rdataset.ttl rrset = objects.RecordSet(**values) rrset.records = objects.RecordList() for rdata in rdataset: rr = objects.Record(data=rdata.to_text()) rrset.records.append(rr) return rrset def bind_tcp(host, port, tcp_backlog): # Bind to the TCP port LOG.info(_LI('Opening TCP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # NOTE: Linux supports socket.SO_REUSEPORT only in 3.9 and later releases. try: sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except Exception: pass sock_tcp.setblocking(True) sock_tcp.bind((host, port)) sock_tcp.listen(tcp_backlog) return sock_tcp def bind_udp(host, port): # Bind to the UDP port LOG.info(_LI('Opening UDP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # NOTE: Linux supports socket.SO_REUSEPORT only in 3.9 and later releases. try: sock_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except Exception: pass sock_udp.setblocking(True) sock_udp.bind((host, port)) return sock_udp def do_axfr(zone_name, servers, timeout=None, source=None): """ Performs an AXFR for a given zone name """ random.shuffle(servers) timeout = timeout or cfg.CONF["service:mdns"].xfr_timeout xfr = None for srv in servers: to = eventlet.Timeout(timeout) log_info = {'name': zone_name, 'host': srv} try: LOG.info(_LI("Doing AXFR for %(name)s from %(host)s") % log_info) xfr = dns.query.xfr(srv['host'], zone_name, relativize=False, timeout=1, port=srv['port'], source=source) raw_zone = dns.zone.from_xfr(xfr, relativize=False) break except eventlet.Timeout as t: if t == to: msg = _LE("AXFR timed out for %(name)s from %(host)s") LOG.error(msg % log_info) continue except dns.exception.FormError: msg = _LE("Domain %(name)s is not present on %(host)s." "Trying next server.") LOG.error(msg % log_info) except socket.error: msg = _LE("Connection error when doing AXFR for %(name)s from " "%(host)s") LOG.error(msg % log_info) except Exception: msg = _LE("Problem doing AXFR %(name)s from %(host)s. " "Trying next server.") LOG.exception(msg % log_info) finally: to.cancel() continue else: msg = _LE("XFR failed for %(name)s. No servers in %(servers)s was " "reached.") raise exceptions.XFRFailure( msg % {"name": zone_name, "servers": servers}) LOG.debug("AXFR Successful for %s" % raw_zone.origin.to_text()) return raw_zone
__call__
identifier_name
dnsutils.py
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Endre Karlson <endre.karlson@hp.com> # # 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 random import socket import base64 import time from threading import Lock import six import dns import dns.exception import dns.zone import eventlet from dns import rdatatype from oslo_log import log as logging from oslo_config import cfg from designate import context from designate import exceptions from designate import objects from designate.i18n import _LE from designate.i18n import _LI LOG = logging.getLogger(__name__) util_opts = [ cfg.IntOpt('xfr_timeout', help="Timeout in seconds for XFR's.", default=10) ] class DNSMiddleware(object): """Base DNS Middleware class with some utility methods""" def __init__(self, application): self.application = application def process_request(self, request): """Called on each request. If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here. """ return None def process_response(self, response): """Do whatever you'd like to the response.""" return response def __call__(self, request): response = self.process_request(request) if response: return response response = self.application(request) return self.process_response(response) def _build_error_response(self): response = dns.message.make_response( dns.message.make_query('unknown', dns.rdatatype.A)) response.set_rcode(dns.rcode.FORMERR) return response class SerializationMiddleware(DNSMiddleware): """DNS Middleware to serialize/deserialize DNS Packets""" def __init__(self, application, tsig_keyring=None): self.application = application self.tsig_keyring = tsig_keyring def __call__(self, request): # Generate the initial context. This may be updated by other middleware # as we learn more information about the Request. ctxt = context.DesignateContext.get_admin_context(all_tenants=True) try: message = dns.message.from_wire(request['payload'], self.tsig_keyring) if message.had_tsig: LOG.debug('Request signed with TSIG key: %s', message.keyname) # Create + Attach the initial "environ" dict. This is similar to # the environ dict used in typical WSGI middleware. message.environ = { 'context': ctxt, 'addr': request['addr'], } except dns.message.UnknownTSIGKey: LOG.error(_LE("Unknown TSIG key from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except dns.tsig.BadSignature: LOG.error(_LE("Invalid TSIG signature from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except dns.exception.DNSException: LOG.error(_LE("Failed to deserialize packet from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except Exception: LOG.exception(_LE("Unknown exception deserializing packet " "from %(host)s %(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() else: # Hand the Deserialized packet onto the Application for response in self.application(message): # Serialize and return the response if present if isinstance(response, dns.message.Message): yield response.to_wire(max_size=65535) elif isinstance(response, dns.renderer.Renderer): yield response.get_wire() class TsigInfoMiddleware(DNSMiddleware): """Middleware which looks up the information available for a TsigKey""" def __init__(self, application, storage): super(TsigInfoMiddleware, self).__init__(application) self.storage = storage def process_request(self, request): if not request.had_tsig: return None try: criterion = {'name': request.keyname.to_text(True)} tsigkey = self.storage.find_tsigkey( context.get_current(), criterion) request.environ['tsigkey'] = tsigkey request.environ['context'].tsigkey_id = tsigkey.id except exceptions.TsigKeyNotFound: # This should never happen, as we just validated the key.. Except # for race conditions.. return self._build_error_response() return None class TsigKeyring(object): """Implements the DNSPython KeyRing API, backed by the Designate DB""" def __init__(self, storage): self.storage = storage def __getitem__(self, key): return self.get(key) def get(self, key, default=None): try: criterion = {'name': key.to_text(True)} tsigkey = self.storage.find_tsigkey( context.get_current(), criterion) return base64.decodestring(tsigkey.secret) except exceptions.TsigKeyNotFound: return default class ZoneLock(object): """A Lock across all zones that enforces a rate limit on NOTIFYs""" def __init__(self, delay): self.lock = Lock() self.data = {} self.delay = delay def acquire(self, zone): with self.lock: # If no one holds the lock for the zone, grant it if zone not in self.data: self.data[zone] = time.time() return True # Otherwise, get the time that it was locked locktime = self.data[zone] now = time.time() period = now - locktime # If it has been locked for longer than the allowed period # give the lock to the new requester if period > self.delay: self.data[zone] = now return True LOG.debug('Lock for %(zone)s can\'t be releaesed for %(period)s' 'seconds' % {'zone': zone, 'period': str(self.delay - period)}) # Don't grant the lock for the zone return False def release(self, zone): # Release the lock with self.lock: try: self.data.pop(zone) except KeyError: pass class LimitNotifyMiddleware(DNSMiddleware): """Middleware that rate limits NOTIFYs to the Agent""" def __init__(self, application): super(LimitNotifyMiddleware, self).__init__(application) self.delay = cfg.CONF['service:agent'].notify_delay self.locker = ZoneLock(self.delay) def process_request(self, request): opcode = request.opcode() if opcode != dns.opcode.NOTIFY: return None zone_name = request.question[0].name.to_text() if self.locker.acquire(zone_name): time.sleep(self.delay) self.locker.release(zone_name) return None else: LOG.debug('Threw away NOTIFY for %(zone)s, already ' 'working on an update.' % {'zone': zone_name}) response = dns.message.make_response(request) # Provide an authoritative answer response.flags |= dns.flags.AA return (response,) def from_dnspython_zone(dnspython_zone): # dnspython never builds a zone with more than one SOA, even if we give # it a zonefile that contains more than one soa = dnspython_zone.get_rdataset(dnspython_zone.origin, 'SOA') if soa is None: raise exceptions.BadRequest('An SOA record is required') email = soa[0].rname.to_text().rstrip('.') email = email.replace('.', '@', 1) values = { 'name': dnspython_zone.origin.to_text(), 'email': email, 'ttl': soa.ttl, 'serial': soa[0].serial, 'retry': soa[0].retry, 'expire': soa[0].expire } zone = objects.Domain(**values) rrsets = dnspyrecords_to_recordsetlist(dnspython_zone.nodes) zone.recordsets = rrsets return zone def dnspyrecords_to_recordsetlist(dnspython_records): rrsets = objects.RecordList() for rname in six.iterkeys(dnspython_records): for rdataset in dnspython_records[rname]: rrset = dnspythonrecord_to_recordset(rname, rdataset) if rrset is None: continue rrsets.append(rrset) return rrsets def dnspythonrecord_to_recordset(rname, rdataset): record_type = rdatatype.to_text(rdataset.rdtype) # Create the other recordsets values = { 'name': rname.to_text(), 'type': record_type } if rdataset.ttl != 0: values['ttl'] = rdataset.ttl rrset = objects.RecordSet(**values) rrset.records = objects.RecordList() for rdata in rdataset:
return rrset def bind_tcp(host, port, tcp_backlog): # Bind to the TCP port LOG.info(_LI('Opening TCP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # NOTE: Linux supports socket.SO_REUSEPORT only in 3.9 and later releases. try: sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except Exception: pass sock_tcp.setblocking(True) sock_tcp.bind((host, port)) sock_tcp.listen(tcp_backlog) return sock_tcp def bind_udp(host, port): # Bind to the UDP port LOG.info(_LI('Opening UDP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # NOTE: Linux supports socket.SO_REUSEPORT only in 3.9 and later releases. try: sock_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except Exception: pass sock_udp.setblocking(True) sock_udp.bind((host, port)) return sock_udp def do_axfr(zone_name, servers, timeout=None, source=None): """ Performs an AXFR for a given zone name """ random.shuffle(servers) timeout = timeout or cfg.CONF["service:mdns"].xfr_timeout xfr = None for srv in servers: to = eventlet.Timeout(timeout) log_info = {'name': zone_name, 'host': srv} try: LOG.info(_LI("Doing AXFR for %(name)s from %(host)s") % log_info) xfr = dns.query.xfr(srv['host'], zone_name, relativize=False, timeout=1, port=srv['port'], source=source) raw_zone = dns.zone.from_xfr(xfr, relativize=False) break except eventlet.Timeout as t: if t == to: msg = _LE("AXFR timed out for %(name)s from %(host)s") LOG.error(msg % log_info) continue except dns.exception.FormError: msg = _LE("Domain %(name)s is not present on %(host)s." "Trying next server.") LOG.error(msg % log_info) except socket.error: msg = _LE("Connection error when doing AXFR for %(name)s from " "%(host)s") LOG.error(msg % log_info) except Exception: msg = _LE("Problem doing AXFR %(name)s from %(host)s. " "Trying next server.") LOG.exception(msg % log_info) finally: to.cancel() continue else: msg = _LE("XFR failed for %(name)s. No servers in %(servers)s was " "reached.") raise exceptions.XFRFailure( msg % {"name": zone_name, "servers": servers}) LOG.debug("AXFR Successful for %s" % raw_zone.origin.to_text()) return raw_zone
rr = objects.Record(data=rdata.to_text()) rrset.records.append(rr)
conditional_block
dnsutils.py
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Endre Karlson <endre.karlson@hp.com> # # 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 random import socket import base64 import time from threading import Lock import six import dns import dns.exception import dns.zone import eventlet from dns import rdatatype from oslo_log import log as logging from oslo_config import cfg from designate import context from designate import exceptions from designate import objects from designate.i18n import _LE from designate.i18n import _LI LOG = logging.getLogger(__name__) util_opts = [ cfg.IntOpt('xfr_timeout', help="Timeout in seconds for XFR's.", default=10) ] class DNSMiddleware(object): """Base DNS Middleware class with some utility methods""" def __init__(self, application): self.application = application def process_request(self, request): """Called on each request. If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here. """ return None def process_response(self, response): """Do whatever you'd like to the response.""" return response def __call__(self, request): response = self.process_request(request) if response: return response response = self.application(request) return self.process_response(response) def _build_error_response(self): response = dns.message.make_response( dns.message.make_query('unknown', dns.rdatatype.A)) response.set_rcode(dns.rcode.FORMERR) return response class SerializationMiddleware(DNSMiddleware): """DNS Middleware to serialize/deserialize DNS Packets""" def __init__(self, application, tsig_keyring=None): self.application = application self.tsig_keyring = tsig_keyring def __call__(self, request): # Generate the initial context. This may be updated by other middleware # as we learn more information about the Request. ctxt = context.DesignateContext.get_admin_context(all_tenants=True) try: message = dns.message.from_wire(request['payload'], self.tsig_keyring) if message.had_tsig: LOG.debug('Request signed with TSIG key: %s', message.keyname) # Create + Attach the initial "environ" dict. This is similar to # the environ dict used in typical WSGI middleware. message.environ = { 'context': ctxt, 'addr': request['addr'], } except dns.message.UnknownTSIGKey: LOG.error(_LE("Unknown TSIG key from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except dns.tsig.BadSignature: LOG.error(_LE("Invalid TSIG signature from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except dns.exception.DNSException: LOG.error(_LE("Failed to deserialize packet from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except Exception: LOG.exception(_LE("Unknown exception deserializing packet " "from %(host)s %(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() else: # Hand the Deserialized packet onto the Application for response in self.application(message): # Serialize and return the response if present if isinstance(response, dns.message.Message): yield response.to_wire(max_size=65535) elif isinstance(response, dns.renderer.Renderer): yield response.get_wire() class TsigInfoMiddleware(DNSMiddleware): """Middleware which looks up the information available for a TsigKey""" def __init__(self, application, storage): super(TsigInfoMiddleware, self).__init__(application) self.storage = storage def process_request(self, request): if not request.had_tsig: return None try: criterion = {'name': request.keyname.to_text(True)} tsigkey = self.storage.find_tsigkey( context.get_current(), criterion) request.environ['tsigkey'] = tsigkey request.environ['context'].tsigkey_id = tsigkey.id except exceptions.TsigKeyNotFound: # This should never happen, as we just validated the key.. Except # for race conditions.. return self._build_error_response() return None class TsigKeyring(object): """Implements the DNSPython KeyRing API, backed by the Designate DB""" def __init__(self, storage): self.storage = storage def __getitem__(self, key): return self.get(key) def get(self, key, default=None): try: criterion = {'name': key.to_text(True)} tsigkey = self.storage.find_tsigkey( context.get_current(), criterion) return base64.decodestring(tsigkey.secret) except exceptions.TsigKeyNotFound: return default class ZoneLock(object): """A Lock across all zones that enforces a rate limit on NOTIFYs""" def __init__(self, delay): self.lock = Lock() self.data = {} self.delay = delay def acquire(self, zone): with self.lock: # If no one holds the lock for the zone, grant it if zone not in self.data: self.data[zone] = time.time() return True # Otherwise, get the time that it was locked locktime = self.data[zone] now = time.time() period = now - locktime # If it has been locked for longer than the allowed period # give the lock to the new requester if period > self.delay: self.data[zone] = now return True LOG.debug('Lock for %(zone)s can\'t be releaesed for %(period)s' 'seconds' % {'zone': zone, 'period': str(self.delay - period)}) # Don't grant the lock for the zone return False def release(self, zone): # Release the lock with self.lock: try: self.data.pop(zone) except KeyError: pass class LimitNotifyMiddleware(DNSMiddleware): """Middleware that rate limits NOTIFYs to the Agent""" def __init__(self, application): super(LimitNotifyMiddleware, self).__init__(application) self.delay = cfg.CONF['service:agent'].notify_delay self.locker = ZoneLock(self.delay) def process_request(self, request): opcode = request.opcode() if opcode != dns.opcode.NOTIFY: return None zone_name = request.question[0].name.to_text() if self.locker.acquire(zone_name): time.sleep(self.delay) self.locker.release(zone_name) return None else: LOG.debug('Threw away NOTIFY for %(zone)s, already ' 'working on an update.' % {'zone': zone_name}) response = dns.message.make_response(request) # Provide an authoritative answer response.flags |= dns.flags.AA return (response,) def from_dnspython_zone(dnspython_zone): # dnspython never builds a zone with more than one SOA, even if we give # it a zonefile that contains more than one soa = dnspython_zone.get_rdataset(dnspython_zone.origin, 'SOA') if soa is None: raise exceptions.BadRequest('An SOA record is required') email = soa[0].rname.to_text().rstrip('.') email = email.replace('.', '@', 1) values = { 'name': dnspython_zone.origin.to_text(), 'email': email, 'ttl': soa.ttl, 'serial': soa[0].serial, 'retry': soa[0].retry, 'expire': soa[0].expire } zone = objects.Domain(**values) rrsets = dnspyrecords_to_recordsetlist(dnspython_zone.nodes) zone.recordsets = rrsets return zone
rrset = dnspythonrecord_to_recordset(rname, rdataset) if rrset is None: continue rrsets.append(rrset) return rrsets def dnspythonrecord_to_recordset(rname, rdataset): record_type = rdatatype.to_text(rdataset.rdtype) # Create the other recordsets values = { 'name': rname.to_text(), 'type': record_type } if rdataset.ttl != 0: values['ttl'] = rdataset.ttl rrset = objects.RecordSet(**values) rrset.records = objects.RecordList() for rdata in rdataset: rr = objects.Record(data=rdata.to_text()) rrset.records.append(rr) return rrset def bind_tcp(host, port, tcp_backlog): # Bind to the TCP port LOG.info(_LI('Opening TCP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # NOTE: Linux supports socket.SO_REUSEPORT only in 3.9 and later releases. try: sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except Exception: pass sock_tcp.setblocking(True) sock_tcp.bind((host, port)) sock_tcp.listen(tcp_backlog) return sock_tcp def bind_udp(host, port): # Bind to the UDP port LOG.info(_LI('Opening UDP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # NOTE: Linux supports socket.SO_REUSEPORT only in 3.9 and later releases. try: sock_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except Exception: pass sock_udp.setblocking(True) sock_udp.bind((host, port)) return sock_udp def do_axfr(zone_name, servers, timeout=None, source=None): """ Performs an AXFR for a given zone name """ random.shuffle(servers) timeout = timeout or cfg.CONF["service:mdns"].xfr_timeout xfr = None for srv in servers: to = eventlet.Timeout(timeout) log_info = {'name': zone_name, 'host': srv} try: LOG.info(_LI("Doing AXFR for %(name)s from %(host)s") % log_info) xfr = dns.query.xfr(srv['host'], zone_name, relativize=False, timeout=1, port=srv['port'], source=source) raw_zone = dns.zone.from_xfr(xfr, relativize=False) break except eventlet.Timeout as t: if t == to: msg = _LE("AXFR timed out for %(name)s from %(host)s") LOG.error(msg % log_info) continue except dns.exception.FormError: msg = _LE("Domain %(name)s is not present on %(host)s." "Trying next server.") LOG.error(msg % log_info) except socket.error: msg = _LE("Connection error when doing AXFR for %(name)s from " "%(host)s") LOG.error(msg % log_info) except Exception: msg = _LE("Problem doing AXFR %(name)s from %(host)s. " "Trying next server.") LOG.exception(msg % log_info) finally: to.cancel() continue else: msg = _LE("XFR failed for %(name)s. No servers in %(servers)s was " "reached.") raise exceptions.XFRFailure( msg % {"name": zone_name, "servers": servers}) LOG.debug("AXFR Successful for %s" % raw_zone.origin.to_text()) return raw_zone
def dnspyrecords_to_recordsetlist(dnspython_records): rrsets = objects.RecordList() for rname in six.iterkeys(dnspython_records): for rdataset in dnspython_records[rname]:
random_line_split
dnsutils.py
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Endre Karlson <endre.karlson@hp.com> # # 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 random import socket import base64 import time from threading import Lock import six import dns import dns.exception import dns.zone import eventlet from dns import rdatatype from oslo_log import log as logging from oslo_config import cfg from designate import context from designate import exceptions from designate import objects from designate.i18n import _LE from designate.i18n import _LI LOG = logging.getLogger(__name__) util_opts = [ cfg.IntOpt('xfr_timeout', help="Timeout in seconds for XFR's.", default=10) ] class DNSMiddleware(object): """Base DNS Middleware class with some utility methods""" def __init__(self, application): self.application = application def process_request(self, request): """Called on each request. If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here. """ return None def process_response(self, response): """Do whatever you'd like to the response.""" return response def __call__(self, request): response = self.process_request(request) if response: return response response = self.application(request) return self.process_response(response) def _build_error_response(self): response = dns.message.make_response( dns.message.make_query('unknown', dns.rdatatype.A)) response.set_rcode(dns.rcode.FORMERR) return response class SerializationMiddleware(DNSMiddleware): """DNS Middleware to serialize/deserialize DNS Packets""" def __init__(self, application, tsig_keyring=None): self.application = application self.tsig_keyring = tsig_keyring def __call__(self, request): # Generate the initial context. This may be updated by other middleware # as we learn more information about the Request. ctxt = context.DesignateContext.get_admin_context(all_tenants=True) try: message = dns.message.from_wire(request['payload'], self.tsig_keyring) if message.had_tsig: LOG.debug('Request signed with TSIG key: %s', message.keyname) # Create + Attach the initial "environ" dict. This is similar to # the environ dict used in typical WSGI middleware. message.environ = { 'context': ctxt, 'addr': request['addr'], } except dns.message.UnknownTSIGKey: LOG.error(_LE("Unknown TSIG key from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except dns.tsig.BadSignature: LOG.error(_LE("Invalid TSIG signature from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except dns.exception.DNSException: LOG.error(_LE("Failed to deserialize packet from %(host)s:" "%(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() except Exception: LOG.exception(_LE("Unknown exception deserializing packet " "from %(host)s %(port)d") % {'host': request['addr'][0], 'port': request['addr'][1]}) response = self._build_error_response() else: # Hand the Deserialized packet onto the Application for response in self.application(message): # Serialize and return the response if present if isinstance(response, dns.message.Message): yield response.to_wire(max_size=65535) elif isinstance(response, dns.renderer.Renderer): yield response.get_wire() class TsigInfoMiddleware(DNSMiddleware): """Middleware which looks up the information available for a TsigKey""" def __init__(self, application, storage): super(TsigInfoMiddleware, self).__init__(application) self.storage = storage def process_request(self, request): if not request.had_tsig: return None try: criterion = {'name': request.keyname.to_text(True)} tsigkey = self.storage.find_tsigkey( context.get_current(), criterion) request.environ['tsigkey'] = tsigkey request.environ['context'].tsigkey_id = tsigkey.id except exceptions.TsigKeyNotFound: # This should never happen, as we just validated the key.. Except # for race conditions.. return self._build_error_response() return None class TsigKeyring(object): """Implements the DNSPython KeyRing API, backed by the Designate DB""" def __init__(self, storage): self.storage = storage def __getitem__(self, key): return self.get(key) def get(self, key, default=None): try: criterion = {'name': key.to_text(True)} tsigkey = self.storage.find_tsigkey( context.get_current(), criterion) return base64.decodestring(tsigkey.secret) except exceptions.TsigKeyNotFound: return default class ZoneLock(object): """A Lock across all zones that enforces a rate limit on NOTIFYs""" def __init__(self, delay): self.lock = Lock() self.data = {} self.delay = delay def acquire(self, zone): with self.lock: # If no one holds the lock for the zone, grant it if zone not in self.data: self.data[zone] = time.time() return True # Otherwise, get the time that it was locked locktime = self.data[zone] now = time.time() period = now - locktime # If it has been locked for longer than the allowed period # give the lock to the new requester if period > self.delay: self.data[zone] = now return True LOG.debug('Lock for %(zone)s can\'t be releaesed for %(period)s' 'seconds' % {'zone': zone, 'period': str(self.delay - period)}) # Don't grant the lock for the zone return False def release(self, zone): # Release the lock with self.lock: try: self.data.pop(zone) except KeyError: pass class LimitNotifyMiddleware(DNSMiddleware): """Middleware that rate limits NOTIFYs to the Agent""" def __init__(self, application): super(LimitNotifyMiddleware, self).__init__(application) self.delay = cfg.CONF['service:agent'].notify_delay self.locker = ZoneLock(self.delay) def process_request(self, request): opcode = request.opcode() if opcode != dns.opcode.NOTIFY: return None zone_name = request.question[0].name.to_text() if self.locker.acquire(zone_name): time.sleep(self.delay) self.locker.release(zone_name) return None else: LOG.debug('Threw away NOTIFY for %(zone)s, already ' 'working on an update.' % {'zone': zone_name}) response = dns.message.make_response(request) # Provide an authoritative answer response.flags |= dns.flags.AA return (response,) def from_dnspython_zone(dnspython_zone): # dnspython never builds a zone with more than one SOA, even if we give # it a zonefile that contains more than one soa = dnspython_zone.get_rdataset(dnspython_zone.origin, 'SOA') if soa is None: raise exceptions.BadRequest('An SOA record is required') email = soa[0].rname.to_text().rstrip('.') email = email.replace('.', '@', 1) values = { 'name': dnspython_zone.origin.to_text(), 'email': email, 'ttl': soa.ttl, 'serial': soa[0].serial, 'retry': soa[0].retry, 'expire': soa[0].expire } zone = objects.Domain(**values) rrsets = dnspyrecords_to_recordsetlist(dnspython_zone.nodes) zone.recordsets = rrsets return zone def dnspyrecords_to_recordsetlist(dnspython_records): rrsets = objects.RecordList() for rname in six.iterkeys(dnspython_records): for rdataset in dnspython_records[rname]: rrset = dnspythonrecord_to_recordset(rname, rdataset) if rrset is None: continue rrsets.append(rrset) return rrsets def dnspythonrecord_to_recordset(rname, rdataset): record_type = rdatatype.to_text(rdataset.rdtype) # Create the other recordsets values = { 'name': rname.to_text(), 'type': record_type } if rdataset.ttl != 0: values['ttl'] = rdataset.ttl rrset = objects.RecordSet(**values) rrset.records = objects.RecordList() for rdata in rdataset: rr = objects.Record(data=rdata.to_text()) rrset.records.append(rr) return rrset def bind_tcp(host, port, tcp_backlog): # Bind to the TCP port
def bind_udp(host, port): # Bind to the UDP port LOG.info(_LI('Opening UDP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # NOTE: Linux supports socket.SO_REUSEPORT only in 3.9 and later releases. try: sock_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except Exception: pass sock_udp.setblocking(True) sock_udp.bind((host, port)) return sock_udp def do_axfr(zone_name, servers, timeout=None, source=None): """ Performs an AXFR for a given zone name """ random.shuffle(servers) timeout = timeout or cfg.CONF["service:mdns"].xfr_timeout xfr = None for srv in servers: to = eventlet.Timeout(timeout) log_info = {'name': zone_name, 'host': srv} try: LOG.info(_LI("Doing AXFR for %(name)s from %(host)s") % log_info) xfr = dns.query.xfr(srv['host'], zone_name, relativize=False, timeout=1, port=srv['port'], source=source) raw_zone = dns.zone.from_xfr(xfr, relativize=False) break except eventlet.Timeout as t: if t == to: msg = _LE("AXFR timed out for %(name)s from %(host)s") LOG.error(msg % log_info) continue except dns.exception.FormError: msg = _LE("Domain %(name)s is not present on %(host)s." "Trying next server.") LOG.error(msg % log_info) except socket.error: msg = _LE("Connection error when doing AXFR for %(name)s from " "%(host)s") LOG.error(msg % log_info) except Exception: msg = _LE("Problem doing AXFR %(name)s from %(host)s. " "Trying next server.") LOG.exception(msg % log_info) finally: to.cancel() continue else: msg = _LE("XFR failed for %(name)s. No servers in %(servers)s was " "reached.") raise exceptions.XFRFailure( msg % {"name": zone_name, "servers": servers}) LOG.debug("AXFR Successful for %s" % raw_zone.origin.to_text()) return raw_zone
LOG.info(_LI('Opening TCP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # NOTE: Linux supports socket.SO_REUSEPORT only in 3.9 and later releases. try: sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except Exception: pass sock_tcp.setblocking(True) sock_tcp.bind((host, port)) sock_tcp.listen(tcp_backlog) return sock_tcp
identifier_body
m2py.py
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. Implicitly assumes e is array_like """ print("%s:" % s) print(e) print("%s.shape:" % s) print(e.shape) print("%s.dtype:" % s) print(e.dtype) print("-------------------------------------------") def
(msg=None): if msg is not None: print(msg) exit(-1) def brk(s, e): """ Used for debugging, just break the script, dumping data. """ dmpdat(s, e) exit(-1) def chkdat(t, s, e, rtol=1e-05, atol=1e-08): """ Check this matrix against data dumped by octave, with given tolerance """ mat = loadmat(os.path.join('check_data', t, s) + '.mat')['ex'] is_equal = np.allclose(e, mat, rtol=rtol, atol=atol) #is_equal = np.array_equal(e, mat) print("%s:%s:iEqual=%d" % (t, s, is_equal)) if not is_equal: dmpdat(s + '<python>', e) dmpdat(s + '<matlab>', mat) np.savetxt(os.path.join("check_data", t, s) + '_python_err', e) np.savetxt(os.path.join("check_data", t, s) + '_matlab_err', mat) print("FAILED check on expr: %s, signal: %s" % (s, t)) #hbrk() return is_equal
hbrk
identifier_name
m2py.py
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. Implicitly assumes e is array_like """ print("%s:" % s) print(e) print("%s.shape:" % s) print(e.shape) print("%s.dtype:" % s) print(e.dtype) print("-------------------------------------------") def hbrk(msg=None):
def brk(s, e): """ Used for debugging, just break the script, dumping data. """ dmpdat(s, e) exit(-1) def chkdat(t, s, e, rtol=1e-05, atol=1e-08): """ Check this matrix against data dumped by octave, with given tolerance """ mat = loadmat(os.path.join('check_data', t, s) + '.mat')['ex'] is_equal = np.allclose(e, mat, rtol=rtol, atol=atol) #is_equal = np.array_equal(e, mat) print("%s:%s:iEqual=%d" % (t, s, is_equal)) if not is_equal: dmpdat(s + '<python>', e) dmpdat(s + '<matlab>', mat) np.savetxt(os.path.join("check_data", t, s) + '_python_err', e) np.savetxt(os.path.join("check_data", t, s) + '_matlab_err', mat) print("FAILED check on expr: %s, signal: %s" % (s, t)) #hbrk() return is_equal
if msg is not None: print(msg) exit(-1)
identifier_body
m2py.py
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. Implicitly assumes e is array_like """ print("%s:" % s) print(e) print("%s.shape:" % s) print(e.shape) print("%s.dtype:" % s) print(e.dtype) print("-------------------------------------------") def hbrk(msg=None): if msg is not None: print(msg) exit(-1) def brk(s, e): """ Used for debugging, just break the script, dumping data. """ dmpdat(s, e) exit(-1) def chkdat(t, s, e, rtol=1e-05, atol=1e-08): """ Check this matrix against data dumped by octave, with given tolerance """ mat = loadmat(os.path.join('check_data', t, s) + '.mat')['ex'] is_equal = np.allclose(e, mat, rtol=rtol, atol=atol) #is_equal = np.array_equal(e, mat) print("%s:%s:iEqual=%d" % (t, s, is_equal)) if not is_equal: dmpdat(s + '<python>', e)
return is_equal
dmpdat(s + '<matlab>', mat) np.savetxt(os.path.join("check_data", t, s) + '_python_err', e) np.savetxt(os.path.join("check_data", t, s) + '_matlab_err', mat) print("FAILED check on expr: %s, signal: %s" % (s, t)) #hbrk()
random_line_split
m2py.py
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. Implicitly assumes e is array_like """ print("%s:" % s) print(e) print("%s.shape:" % s) print(e.shape) print("%s.dtype:" % s) print(e.dtype) print("-------------------------------------------") def hbrk(msg=None): if msg is not None:
exit(-1) def brk(s, e): """ Used for debugging, just break the script, dumping data. """ dmpdat(s, e) exit(-1) def chkdat(t, s, e, rtol=1e-05, atol=1e-08): """ Check this matrix against data dumped by octave, with given tolerance """ mat = loadmat(os.path.join('check_data', t, s) + '.mat')['ex'] is_equal = np.allclose(e, mat, rtol=rtol, atol=atol) #is_equal = np.array_equal(e, mat) print("%s:%s:iEqual=%d" % (t, s, is_equal)) if not is_equal: dmpdat(s + '<python>', e) dmpdat(s + '<matlab>', mat) np.savetxt(os.path.join("check_data", t, s) + '_python_err', e) np.savetxt(os.path.join("check_data", t, s) + '_matlab_err', mat) print("FAILED check on expr: %s, signal: %s" % (s, t)) #hbrk() return is_equal
print(msg)
conditional_block
auto_config.py
""" Auto Configuration Helper """ import logging import os import requests from urlparse import urlparse from constants import InsightsConstants as constants from cert_auth import rhsmCertificate from connection import InsightsConnection from config import CONFIG as config logger = logging.getLogger(__name__) APP_NAME = constants.app_name def verify_connectivity(): """ Verify connectivity to satellite server """ logger.debug("Verifying Connectivity") ic = InsightsConnection() try: branch_info = ic.branch_info() except requests.ConnectionError as e: logger.debug(e) logger.debug("Failed to connect to satellite") return False except LookupError as e: logger.debug(e) logger.debug("Failed to parse response from satellite") return False try: remote_leaf = branch_info['remote_leaf'] return remote_leaf except LookupError as e: logger.debug(e) logger.debug("Failed to find accurate branch_info") return False def set_auto_configuration(hostname, ca_cert, proxy): """ Set config based on discovered data """ logger.debug("Attempting to auto configure!") logger.debug("Attempting to auto configure hostname: %s", hostname) logger.debug("Attempting to auto configure CA cert: %s", ca_cert) logger.debug("Attempting to auto configure proxy: %s", proxy) saved_base_url = config['base_url'] if ca_cert is not None: saved_cert_verify = config['cert_verify'] config['cert_verify'] = ca_cert if proxy is not None: saved_proxy = config['proxy'] config['proxy'] = proxy config['base_url'] = hostname + '/r/insights' if not verify_connectivity(): logger.warn("Could not auto configure, falling back to static config") logger.warn("See %s for additional information", constants.default_log_file) config['base_url'] = saved_base_url if proxy is not None: if saved_proxy is not None and saved_proxy.lower() == 'none': saved_proxy = None config['proxy'] = saved_proxy if ca_cert is not None: config['cert_verify'] = saved_cert_verify def _try_satellite6_configuration(): """ Try to autoconfigure for Satellite 6 """ try: from rhsm.config import initConfig rhsm_config = initConfig() logger.debug('Trying to autoconf Satellite 6') cert = file(rhsmCertificate.certpath(), 'r').read() key = file(rhsmCertificate.keypath(), 'r').read() rhsm = rhsmCertificate(key, cert) # This will throw an exception if we are not registered logger.debug('Checking if system is subscription-manager registered') rhsm.getConsumerId() logger.debug('System is subscription-manager registered') rhsm_hostname = rhsm_config.get('server', 'hostname') rhsm_hostport = rhsm_config.get('server', 'port') rhsm_proxy_hostname = rhsm_config.get('server', 'proxy_hostname').strip() rhsm_proxy_port = rhsm_config.get('server', 'proxy_port').strip() rhsm_proxy_user = rhsm_config.get('server', 'proxy_user').strip() rhsm_proxy_pass = rhsm_config.get('server', 'proxy_password').strip() proxy = None if rhsm_proxy_hostname != "": logger.debug("Found rhsm_proxy_hostname %s", rhsm_proxy_hostname) proxy = "http://" if rhsm_proxy_user != "" and rhsm_proxy_pass != "": logger.debug("Found user and password for rhsm_proxy") proxy = proxy + rhsm_proxy_user + ":" + rhsm_proxy_pass + "@" proxy = proxy + rhsm_proxy_hostname + ':' + rhsm_proxy_port logger.debug("RHSM Proxy: %s", proxy) logger.debug("Found Satellite Server Host: %s, Port: %s", rhsm_hostname, rhsm_hostport) rhsm_ca = rhsm_config.get('rhsm', 'repo_ca_cert') logger.debug("Found CA: %s", rhsm_ca) logger.debug("Setting authmethod to CERT") config['authmethod'] = 'CERT' # Directly connected to Red Hat, use cert auth directly with the api if (rhsm_hostname == 'subscription.rhn.redhat.com' or rhsm_hostname == 'subscription.rhsm.redhat.com'): logger.debug("Connected to Red Hat Directly, using cert-api") rhsm_hostname = 'cert-api.access.redhat.com' rhsm_ca = None else: # Set the host path # 'rhsm_hostname' should really be named ~ 'rhsm_host_base_url' rhsm_hostname = rhsm_hostname + ':' + rhsm_hostport + '/redhat_access' logger.debug("Trying to set auto_configuration") set_auto_configuration(rhsm_hostname, rhsm_ca, proxy) return True except Exception as e: logger.debug(e) logger.debug('System is NOT subscription-manager registered') return False def _read_systemid_file(path): with open(path, "r") as systemid: data = systemid.read().replace('\n', '') return data def _try_satellite5_configuration(): """ Attempt to determine Satellite 5 Configuration """ logger.debug("Trying Satellite 5 auto_config") rhn_config = '/etc/sysconfig/rhn/up2date' systemid = '/etc/sysconfig/rhn/systemid' if os.path.isfile(rhn_config): if os.path.isfile(systemid): config['systemid'] = _read_systemid_file(systemid) else: logger.debug("Could not find Satellite 5 systemid file.") return False logger.debug("Found Satellite 5 Config") rhn_conf_file = file(rhn_config, 'r') hostname = None for line in rhn_conf_file: if line.startswith('serverURL='): url = urlparse(line.split('=')[1]) hostname = url.netloc + '/redhat_access' logger.debug("Found hostname %s", hostname) if line.startswith('sslCACert='): rhn_ca = line.strip().split('=')[1] # Auto discover proxy stuff if line.startswith('enableProxy='): proxy_enabled = line.strip().split('=')[1] if line.startswith('httpProxy='): proxy_host_port = line.strip().split('=')[1] if line.startswith('proxyUser='):
if line.startswith('proxyPassword='): proxy_password = line.strip().split('=')[1] if hostname: proxy = None if proxy_enabled == "1": proxy = "http://" if proxy_user != "" and proxy_password != "": logger.debug("Found user and password for rhn_proxy") proxy = proxy + proxy_user + ':' + proxy_password proxy = proxy + "@" + proxy_host_port else: proxy = proxy + proxy_host_port logger.debug("RHN Proxy: %s", proxy) set_auto_configuration(hostname, rhn_ca, proxy) else: logger.debug("Could not find hostname") return False return True else: logger.debug("Could not find rhn config") return False def try_auto_configuration(): """ Try to auto-configure if we are attached to a sat5/6 """ if config['auto_config'] and not config['offline']: if not _try_satellite6_configuration(): _try_satellite5_configuration()
proxy_user = line.strip().split('=')[1]
conditional_block
auto_config.py
""" Auto Configuration Helper """ import logging import os import requests from urlparse import urlparse from constants import InsightsConstants as constants from cert_auth import rhsmCertificate from connection import InsightsConnection from config import CONFIG as config logger = logging.getLogger(__name__) APP_NAME = constants.app_name def verify_connectivity(): """ Verify connectivity to satellite server """ logger.debug("Verifying Connectivity") ic = InsightsConnection() try: branch_info = ic.branch_info() except requests.ConnectionError as e: logger.debug(e) logger.debug("Failed to connect to satellite") return False except LookupError as e: logger.debug(e) logger.debug("Failed to parse response from satellite") return False try: remote_leaf = branch_info['remote_leaf'] return remote_leaf except LookupError as e: logger.debug(e) logger.debug("Failed to find accurate branch_info") return False def set_auto_configuration(hostname, ca_cert, proxy): """ Set config based on discovered data """ logger.debug("Attempting to auto configure!") logger.debug("Attempting to auto configure hostname: %s", hostname) logger.debug("Attempting to auto configure CA cert: %s", ca_cert) logger.debug("Attempting to auto configure proxy: %s", proxy) saved_base_url = config['base_url'] if ca_cert is not None: saved_cert_verify = config['cert_verify'] config['cert_verify'] = ca_cert if proxy is not None: saved_proxy = config['proxy'] config['proxy'] = proxy config['base_url'] = hostname + '/r/insights' if not verify_connectivity(): logger.warn("Could not auto configure, falling back to static config") logger.warn("See %s for additional information", constants.default_log_file) config['base_url'] = saved_base_url if proxy is not None: if saved_proxy is not None and saved_proxy.lower() == 'none': saved_proxy = None config['proxy'] = saved_proxy if ca_cert is not None: config['cert_verify'] = saved_cert_verify def _try_satellite6_configuration():
def _read_systemid_file(path): with open(path, "r") as systemid: data = systemid.read().replace('\n', '') return data def _try_satellite5_configuration(): """ Attempt to determine Satellite 5 Configuration """ logger.debug("Trying Satellite 5 auto_config") rhn_config = '/etc/sysconfig/rhn/up2date' systemid = '/etc/sysconfig/rhn/systemid' if os.path.isfile(rhn_config): if os.path.isfile(systemid): config['systemid'] = _read_systemid_file(systemid) else: logger.debug("Could not find Satellite 5 systemid file.") return False logger.debug("Found Satellite 5 Config") rhn_conf_file = file(rhn_config, 'r') hostname = None for line in rhn_conf_file: if line.startswith('serverURL='): url = urlparse(line.split('=')[1]) hostname = url.netloc + '/redhat_access' logger.debug("Found hostname %s", hostname) if line.startswith('sslCACert='): rhn_ca = line.strip().split('=')[1] # Auto discover proxy stuff if line.startswith('enableProxy='): proxy_enabled = line.strip().split('=')[1] if line.startswith('httpProxy='): proxy_host_port = line.strip().split('=')[1] if line.startswith('proxyUser='): proxy_user = line.strip().split('=')[1] if line.startswith('proxyPassword='): proxy_password = line.strip().split('=')[1] if hostname: proxy = None if proxy_enabled == "1": proxy = "http://" if proxy_user != "" and proxy_password != "": logger.debug("Found user and password for rhn_proxy") proxy = proxy + proxy_user + ':' + proxy_password proxy = proxy + "@" + proxy_host_port else: proxy = proxy + proxy_host_port logger.debug("RHN Proxy: %s", proxy) set_auto_configuration(hostname, rhn_ca, proxy) else: logger.debug("Could not find hostname") return False return True else: logger.debug("Could not find rhn config") return False def try_auto_configuration(): """ Try to auto-configure if we are attached to a sat5/6 """ if config['auto_config'] and not config['offline']: if not _try_satellite6_configuration(): _try_satellite5_configuration()
""" Try to autoconfigure for Satellite 6 """ try: from rhsm.config import initConfig rhsm_config = initConfig() logger.debug('Trying to autoconf Satellite 6') cert = file(rhsmCertificate.certpath(), 'r').read() key = file(rhsmCertificate.keypath(), 'r').read() rhsm = rhsmCertificate(key, cert) # This will throw an exception if we are not registered logger.debug('Checking if system is subscription-manager registered') rhsm.getConsumerId() logger.debug('System is subscription-manager registered') rhsm_hostname = rhsm_config.get('server', 'hostname') rhsm_hostport = rhsm_config.get('server', 'port') rhsm_proxy_hostname = rhsm_config.get('server', 'proxy_hostname').strip() rhsm_proxy_port = rhsm_config.get('server', 'proxy_port').strip() rhsm_proxy_user = rhsm_config.get('server', 'proxy_user').strip() rhsm_proxy_pass = rhsm_config.get('server', 'proxy_password').strip() proxy = None if rhsm_proxy_hostname != "": logger.debug("Found rhsm_proxy_hostname %s", rhsm_proxy_hostname) proxy = "http://" if rhsm_proxy_user != "" and rhsm_proxy_pass != "": logger.debug("Found user and password for rhsm_proxy") proxy = proxy + rhsm_proxy_user + ":" + rhsm_proxy_pass + "@" proxy = proxy + rhsm_proxy_hostname + ':' + rhsm_proxy_port logger.debug("RHSM Proxy: %s", proxy) logger.debug("Found Satellite Server Host: %s, Port: %s", rhsm_hostname, rhsm_hostport) rhsm_ca = rhsm_config.get('rhsm', 'repo_ca_cert') logger.debug("Found CA: %s", rhsm_ca) logger.debug("Setting authmethod to CERT") config['authmethod'] = 'CERT' # Directly connected to Red Hat, use cert auth directly with the api if (rhsm_hostname == 'subscription.rhn.redhat.com' or rhsm_hostname == 'subscription.rhsm.redhat.com'): logger.debug("Connected to Red Hat Directly, using cert-api") rhsm_hostname = 'cert-api.access.redhat.com' rhsm_ca = None else: # Set the host path # 'rhsm_hostname' should really be named ~ 'rhsm_host_base_url' rhsm_hostname = rhsm_hostname + ':' + rhsm_hostport + '/redhat_access' logger.debug("Trying to set auto_configuration") set_auto_configuration(rhsm_hostname, rhsm_ca, proxy) return True except Exception as e: logger.debug(e) logger.debug('System is NOT subscription-manager registered') return False
identifier_body
auto_config.py
""" Auto Configuration Helper """ import logging import os import requests from urlparse import urlparse from constants import InsightsConstants as constants from cert_auth import rhsmCertificate from connection import InsightsConnection from config import CONFIG as config logger = logging.getLogger(__name__) APP_NAME = constants.app_name def verify_connectivity(): """ Verify connectivity to satellite server """ logger.debug("Verifying Connectivity") ic = InsightsConnection() try: branch_info = ic.branch_info() except requests.ConnectionError as e: logger.debug(e) logger.debug("Failed to connect to satellite") return False except LookupError as e: logger.debug(e) logger.debug("Failed to parse response from satellite") return False try: remote_leaf = branch_info['remote_leaf'] return remote_leaf except LookupError as e: logger.debug(e) logger.debug("Failed to find accurate branch_info") return False def set_auto_configuration(hostname, ca_cert, proxy): """ Set config based on discovered data """ logger.debug("Attempting to auto configure!") logger.debug("Attempting to auto configure hostname: %s", hostname) logger.debug("Attempting to auto configure CA cert: %s", ca_cert) logger.debug("Attempting to auto configure proxy: %s", proxy) saved_base_url = config['base_url'] if ca_cert is not None: saved_cert_verify = config['cert_verify'] config['cert_verify'] = ca_cert if proxy is not None: saved_proxy = config['proxy'] config['proxy'] = proxy config['base_url'] = hostname + '/r/insights' if not verify_connectivity(): logger.warn("Could not auto configure, falling back to static config") logger.warn("See %s for additional information", constants.default_log_file) config['base_url'] = saved_base_url if proxy is not None: if saved_proxy is not None and saved_proxy.lower() == 'none': saved_proxy = None config['proxy'] = saved_proxy if ca_cert is not None: config['cert_verify'] = saved_cert_verify def _try_satellite6_configuration(): """ Try to autoconfigure for Satellite 6 """ try: from rhsm.config import initConfig rhsm_config = initConfig() logger.debug('Trying to autoconf Satellite 6') cert = file(rhsmCertificate.certpath(), 'r').read() key = file(rhsmCertificate.keypath(), 'r').read() rhsm = rhsmCertificate(key, cert) # This will throw an exception if we are not registered logger.debug('Checking if system is subscription-manager registered') rhsm.getConsumerId() logger.debug('System is subscription-manager registered') rhsm_hostname = rhsm_config.get('server', 'hostname') rhsm_hostport = rhsm_config.get('server', 'port') rhsm_proxy_hostname = rhsm_config.get('server', 'proxy_hostname').strip() rhsm_proxy_port = rhsm_config.get('server', 'proxy_port').strip() rhsm_proxy_user = rhsm_config.get('server', 'proxy_user').strip() rhsm_proxy_pass = rhsm_config.get('server', 'proxy_password').strip() proxy = None if rhsm_proxy_hostname != "": logger.debug("Found rhsm_proxy_hostname %s", rhsm_proxy_hostname) proxy = "http://" if rhsm_proxy_user != "" and rhsm_proxy_pass != "": logger.debug("Found user and password for rhsm_proxy") proxy = proxy + rhsm_proxy_user + ":" + rhsm_proxy_pass + "@" proxy = proxy + rhsm_proxy_hostname + ':' + rhsm_proxy_port logger.debug("RHSM Proxy: %s", proxy) logger.debug("Found Satellite Server Host: %s, Port: %s", rhsm_hostname, rhsm_hostport) rhsm_ca = rhsm_config.get('rhsm', 'repo_ca_cert') logger.debug("Found CA: %s", rhsm_ca) logger.debug("Setting authmethod to CERT") config['authmethod'] = 'CERT' # Directly connected to Red Hat, use cert auth directly with the api if (rhsm_hostname == 'subscription.rhn.redhat.com' or rhsm_hostname == 'subscription.rhsm.redhat.com'): logger.debug("Connected to Red Hat Directly, using cert-api") rhsm_hostname = 'cert-api.access.redhat.com' rhsm_ca = None else: # Set the host path # 'rhsm_hostname' should really be named ~ 'rhsm_host_base_url' rhsm_hostname = rhsm_hostname + ':' + rhsm_hostport + '/redhat_access' logger.debug("Trying to set auto_configuration") set_auto_configuration(rhsm_hostname, rhsm_ca, proxy) return True except Exception as e: logger.debug(e) logger.debug('System is NOT subscription-manager registered') return False def _read_systemid_file(path): with open(path, "r") as systemid: data = systemid.read().replace('\n', '') return data def _try_satellite5_configuration(): """ Attempt to determine Satellite 5 Configuration """ logger.debug("Trying Satellite 5 auto_config") rhn_config = '/etc/sysconfig/rhn/up2date' systemid = '/etc/sysconfig/rhn/systemid' if os.path.isfile(rhn_config): if os.path.isfile(systemid): config['systemid'] = _read_systemid_file(systemid) else: logger.debug("Could not find Satellite 5 systemid file.") return False logger.debug("Found Satellite 5 Config")
hostname = None for line in rhn_conf_file: if line.startswith('serverURL='): url = urlparse(line.split('=')[1]) hostname = url.netloc + '/redhat_access' logger.debug("Found hostname %s", hostname) if line.startswith('sslCACert='): rhn_ca = line.strip().split('=')[1] # Auto discover proxy stuff if line.startswith('enableProxy='): proxy_enabled = line.strip().split('=')[1] if line.startswith('httpProxy='): proxy_host_port = line.strip().split('=')[1] if line.startswith('proxyUser='): proxy_user = line.strip().split('=')[1] if line.startswith('proxyPassword='): proxy_password = line.strip().split('=')[1] if hostname: proxy = None if proxy_enabled == "1": proxy = "http://" if proxy_user != "" and proxy_password != "": logger.debug("Found user and password for rhn_proxy") proxy = proxy + proxy_user + ':' + proxy_password proxy = proxy + "@" + proxy_host_port else: proxy = proxy + proxy_host_port logger.debug("RHN Proxy: %s", proxy) set_auto_configuration(hostname, rhn_ca, proxy) else: logger.debug("Could not find hostname") return False return True else: logger.debug("Could not find rhn config") return False def try_auto_configuration(): """ Try to auto-configure if we are attached to a sat5/6 """ if config['auto_config'] and not config['offline']: if not _try_satellite6_configuration(): _try_satellite5_configuration()
rhn_conf_file = file(rhn_config, 'r')
random_line_split
auto_config.py
""" Auto Configuration Helper """ import logging import os import requests from urlparse import urlparse from constants import InsightsConstants as constants from cert_auth import rhsmCertificate from connection import InsightsConnection from config import CONFIG as config logger = logging.getLogger(__name__) APP_NAME = constants.app_name def verify_connectivity(): """ Verify connectivity to satellite server """ logger.debug("Verifying Connectivity") ic = InsightsConnection() try: branch_info = ic.branch_info() except requests.ConnectionError as e: logger.debug(e) logger.debug("Failed to connect to satellite") return False except LookupError as e: logger.debug(e) logger.debug("Failed to parse response from satellite") return False try: remote_leaf = branch_info['remote_leaf'] return remote_leaf except LookupError as e: logger.debug(e) logger.debug("Failed to find accurate branch_info") return False def set_auto_configuration(hostname, ca_cert, proxy): """ Set config based on discovered data """ logger.debug("Attempting to auto configure!") logger.debug("Attempting to auto configure hostname: %s", hostname) logger.debug("Attempting to auto configure CA cert: %s", ca_cert) logger.debug("Attempting to auto configure proxy: %s", proxy) saved_base_url = config['base_url'] if ca_cert is not None: saved_cert_verify = config['cert_verify'] config['cert_verify'] = ca_cert if proxy is not None: saved_proxy = config['proxy'] config['proxy'] = proxy config['base_url'] = hostname + '/r/insights' if not verify_connectivity(): logger.warn("Could not auto configure, falling back to static config") logger.warn("See %s for additional information", constants.default_log_file) config['base_url'] = saved_base_url if proxy is not None: if saved_proxy is not None and saved_proxy.lower() == 'none': saved_proxy = None config['proxy'] = saved_proxy if ca_cert is not None: config['cert_verify'] = saved_cert_verify def
(): """ Try to autoconfigure for Satellite 6 """ try: from rhsm.config import initConfig rhsm_config = initConfig() logger.debug('Trying to autoconf Satellite 6') cert = file(rhsmCertificate.certpath(), 'r').read() key = file(rhsmCertificate.keypath(), 'r').read() rhsm = rhsmCertificate(key, cert) # This will throw an exception if we are not registered logger.debug('Checking if system is subscription-manager registered') rhsm.getConsumerId() logger.debug('System is subscription-manager registered') rhsm_hostname = rhsm_config.get('server', 'hostname') rhsm_hostport = rhsm_config.get('server', 'port') rhsm_proxy_hostname = rhsm_config.get('server', 'proxy_hostname').strip() rhsm_proxy_port = rhsm_config.get('server', 'proxy_port').strip() rhsm_proxy_user = rhsm_config.get('server', 'proxy_user').strip() rhsm_proxy_pass = rhsm_config.get('server', 'proxy_password').strip() proxy = None if rhsm_proxy_hostname != "": logger.debug("Found rhsm_proxy_hostname %s", rhsm_proxy_hostname) proxy = "http://" if rhsm_proxy_user != "" and rhsm_proxy_pass != "": logger.debug("Found user and password for rhsm_proxy") proxy = proxy + rhsm_proxy_user + ":" + rhsm_proxy_pass + "@" proxy = proxy + rhsm_proxy_hostname + ':' + rhsm_proxy_port logger.debug("RHSM Proxy: %s", proxy) logger.debug("Found Satellite Server Host: %s, Port: %s", rhsm_hostname, rhsm_hostport) rhsm_ca = rhsm_config.get('rhsm', 'repo_ca_cert') logger.debug("Found CA: %s", rhsm_ca) logger.debug("Setting authmethod to CERT") config['authmethod'] = 'CERT' # Directly connected to Red Hat, use cert auth directly with the api if (rhsm_hostname == 'subscription.rhn.redhat.com' or rhsm_hostname == 'subscription.rhsm.redhat.com'): logger.debug("Connected to Red Hat Directly, using cert-api") rhsm_hostname = 'cert-api.access.redhat.com' rhsm_ca = None else: # Set the host path # 'rhsm_hostname' should really be named ~ 'rhsm_host_base_url' rhsm_hostname = rhsm_hostname + ':' + rhsm_hostport + '/redhat_access' logger.debug("Trying to set auto_configuration") set_auto_configuration(rhsm_hostname, rhsm_ca, proxy) return True except Exception as e: logger.debug(e) logger.debug('System is NOT subscription-manager registered') return False def _read_systemid_file(path): with open(path, "r") as systemid: data = systemid.read().replace('\n', '') return data def _try_satellite5_configuration(): """ Attempt to determine Satellite 5 Configuration """ logger.debug("Trying Satellite 5 auto_config") rhn_config = '/etc/sysconfig/rhn/up2date' systemid = '/etc/sysconfig/rhn/systemid' if os.path.isfile(rhn_config): if os.path.isfile(systemid): config['systemid'] = _read_systemid_file(systemid) else: logger.debug("Could not find Satellite 5 systemid file.") return False logger.debug("Found Satellite 5 Config") rhn_conf_file = file(rhn_config, 'r') hostname = None for line in rhn_conf_file: if line.startswith('serverURL='): url = urlparse(line.split('=')[1]) hostname = url.netloc + '/redhat_access' logger.debug("Found hostname %s", hostname) if line.startswith('sslCACert='): rhn_ca = line.strip().split('=')[1] # Auto discover proxy stuff if line.startswith('enableProxy='): proxy_enabled = line.strip().split('=')[1] if line.startswith('httpProxy='): proxy_host_port = line.strip().split('=')[1] if line.startswith('proxyUser='): proxy_user = line.strip().split('=')[1] if line.startswith('proxyPassword='): proxy_password = line.strip().split('=')[1] if hostname: proxy = None if proxy_enabled == "1": proxy = "http://" if proxy_user != "" and proxy_password != "": logger.debug("Found user and password for rhn_proxy") proxy = proxy + proxy_user + ':' + proxy_password proxy = proxy + "@" + proxy_host_port else: proxy = proxy + proxy_host_port logger.debug("RHN Proxy: %s", proxy) set_auto_configuration(hostname, rhn_ca, proxy) else: logger.debug("Could not find hostname") return False return True else: logger.debug("Could not find rhn config") return False def try_auto_configuration(): """ Try to auto-configure if we are attached to a sat5/6 """ if config['auto_config'] and not config['offline']: if not _try_satellite6_configuration(): _try_satellite5_configuration()
_try_satellite6_configuration
identifier_name
doc2vector.py
# -*- coding: UTF-8 -*- import sys sys.path.append("./") import pandas as pd import gensim from utility.mongodb import MongoDBManager from utility.sentence import segment, sent2vec class Doc2Vector(object): """ 文本转向量 """ def __init__(self): """ :param keep_val: 设定的阈值 """ self.mongo_db = MongoDBManager() def doc2vect(self): """ 所有文档转成向量存储到数据库 :return: """ model = gensim.models.Doc2Vec.load('./models/doc2vec_v1.model') df_data = pd.read_excel("./data/new_prd.xlsx", names=["SysNo", "Title", "Content"]) content = [] title = [] for idx, row in df_data.iterrows(): seg_title = segment(row.Title) seg_content = segment(row.Content) # 转向量 content_vect = sent2vec(model, ' '.join(seg_content)) title_vect = sent2vec(model, ' '.join(seg_title)) content_vect = map(str, content_vect.tolist()) title_vect = map(str, title_vect.tolist())
title.append({"_id": int(idx) + 1, "data": list(title_vect)}) self.mongo_db.insert("content_vector", content) self.mongo_db.insert("title_vector", title) print("finished") if __name__ == '__main__': doc2vect = Doc2Vector() doc2vect.doc2vect()
content.append({"_id": int(idx) + 1, "data": list(content_vect)})
random_line_split
doc2vector.py
# -*- coding: UTF-8 -*- import sys sys.path.append("./") import pandas as pd import gensim from utility.mongodb import MongoDBManager from utility.sentence import segment, sent2vec class Doc2Vector(object): """ 文本转向量 """ def __init__(s
""" :param keep_val: 设定的阈值 """ self.mongo_db = MongoDBManager() def doc2vect(self): """ 所有文档转成向量存储到数据库 :return: """ model = gensim.models.Doc2Vec.load('./models/doc2vec_v1.model') df_data = pd.read_excel("./data/new_prd.xlsx", names=["SysNo", "Title", "Content"]) content = [] title = [] for idx, row in df_data.iterrows(): seg_title = segment(row.Title) seg_content = segment(row.Content) # 转向量 content_vect = sent2vec(model, ' '.join(seg_content)) title_vect = sent2vec(model, ' '.join(seg_title)) content_vect = map(str, content_vect.tolist()) title_vect = map(str, title_vect.tolist()) content.append({"_id": int(idx) + 1, "data": list(content_vect)}) title.append({"_id": int(idx) + 1, "data": list(title_vect)}) self.mongo_db.insert("content_vector", content) self.mongo_db.insert("title_vector", title) print("finished") if __name__ == '__main__': doc2vect = Doc2Vector() doc2vect.doc2vect()
elf):
identifier_name
doc2vector.py
# -*- coding: UTF-8 -*- import sys sys.path.append("./") import pandas as pd import gensim from utility.mongodb import MongoDBManager from utility.sentence import segment, sent2vec class Doc2Vector(object): """ 文本转向量 """ def __init__(self): """ :param keep_val: 设定的阈值 """ self.mongo_db = MongoDBManager() def doc2vect(self): """ 所有文档转成向量存储到数据库 :return: """ model = gensim.models.Doc2Vec.load('./models/doc2vec_v1.model') df_data = pd.read_excel("./data/new_prd.xlsx", names=["SysNo", "Title", "Content"]) content = [] title = [] for idx, row in df_data.iterrows(): seg_title = segment(row.Title) seg_c
nt) self.mongo_db.insert("title_vector", title) print("finished") if __name__ == '__main__': doc2vect = Doc2Vector() doc2vect.doc2vect()
ontent = segment(row.Content) # 转向量 content_vect = sent2vec(model, ' '.join(seg_content)) title_vect = sent2vec(model, ' '.join(seg_title)) content_vect = map(str, content_vect.tolist()) title_vect = map(str, title_vect.tolist()) content.append({"_id": int(idx) + 1, "data": list(content_vect)}) title.append({"_id": int(idx) + 1, "data": list(title_vect)}) self.mongo_db.insert("content_vector", conte
conditional_block
doc2vector.py
# -*- coding: UTF-8 -*- import sys sys.path.append("./") import pandas as pd import gensim from utility.mongodb import MongoDBManager from utility.sentence import segment, sent2vec class Doc2Vector(object):
r() doc2vect.doc2vect()
""" 文本转向量 """ def __init__(self): """ :param keep_val: 设定的阈值 """ self.mongo_db = MongoDBManager() def doc2vect(self): """ 所有文档转成向量存储到数据库 :return: """ model = gensim.models.Doc2Vec.load('./models/doc2vec_v1.model') df_data = pd.read_excel("./data/new_prd.xlsx", names=["SysNo", "Title", "Content"]) content = [] title = [] for idx, row in df_data.iterrows(): seg_title = segment(row.Title) seg_content = segment(row.Content) # 转向量 content_vect = sent2vec(model, ' '.join(seg_content)) title_vect = sent2vec(model, ' '.join(seg_title)) content_vect = map(str, content_vect.tolist()) title_vect = map(str, title_vect.tolist()) content.append({"_id": int(idx) + 1, "data": list(content_vect)}) title.append({"_id": int(idx) + 1, "data": list(title_vect)}) self.mongo_db.insert("content_vector", content) self.mongo_db.insert("title_vector", title) print("finished") if __name__ == '__main__': doc2vect = Doc2Vecto
identifier_body
app.js
'use strict'; jQuery(document).ready(function ($) { var lastId, topMenu = $("#top-navigation"), topMenuHeight = topMenu.outerHeight(), // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function () { var item = $($(this).attr("href")); if (item.length) { return item; } }); //Get width of container var containerWidth = $('.section .container').width(); //Resize animated triangle $(".triangle").css({ "border-left": containerWidth / 2 + 'px outset transparent', "border-right": containerWidth / 2 + 'px outset transparent' }); //resize $(window).resize(function () { containerWidth = $('.container').width(); $(".triangle").css({ "border-left": containerWidth / 2 + 'px outset transparent', "border-right": containerWidth / 2 + 'px outset transparent' }); }); //mask $('.has-mask').each( function() { var $this = $( this ), mask = $this.data( 'aria-mask' ); $this.mask( mask ); }); //Initialize header slider. $('#da-slider').cslider(); //Initial mixitup, used for animated filtering portgolio. $('#portfolio-grid').mixitup({ 'onMixStart': function (config) { $('div.toggleDiv').hide(); } }); //Initial Out clients slider in client section $('#clint-slider').bxSlider({ pager: false, minSlides: 1, maxSlides: 5, moveSlides: 2, slideWidth: 210, slideMargin: 25, prevSelector: $('#client-prev'), nextSelector: $('#client-next'), prevText: '<i class="icon-left-open"></i>', nextText: '<i class="icon-right-open"></i>' }); $('input, textarea').placeholder(); // Bind to scroll $(window).scroll(function () { //Display or hide scroll to top button if ($(this).scrollTop() > 100) { $('.scrollup').fadeIn(); } else { $('.scrollup').fadeOut(); } if ($(this).scrollTop() > 100) { $('.navbar').addClass('navbar-fixed-top animated fadeInDown'); } else { $('.navbar').removeClass('navbar-fixed-top animated fadeInDown'); } // Get container scroll position var fromTop = $(this).scrollTop() + topMenuHeight + 10; // Get id of current scroll item var cur = scrollItems.map(function () { if ($(this).offset().top < fromTop) return this; }); // Get the id of the current element cur = cur[cur.length - 1]; var id = cur && cur.length ? cur[0].id : ""; if (lastId !== id) { lastId = id; // Set/remove active class menuItems .parent().removeClass("active") .end().filter("[href=#" + id + "]").parent().addClass("active"); } }); /* Function for scroliing to top ************************************/ $('.scrollup').click(function () { $("html, body").animate({ scrollTop: 0 }, 600); return false; }); /* Sand newsletter **********************************************************************/ $('#subscribe').click(function () { var error = false; var emailCompare = /^([a-z0-9_.-]+)@([0-9a-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input var email = $('input#nlmail').val().toLowerCase(); // get the value of the input field if (email == "" || email == " " || !emailCompare.test(email)) { $('#err-subscribe').show(500); $('#err-subscribe').delay(4000); $('#err-subscribe').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } if (error === false) { $.ajax({ type: 'POST', url: 'php/newsletter.php', data: { email: $('#nlmail').val() }, error: function (request, error) { alert("An error occurred"); }, success: function (response) { if (response == 'OK') { $('#success-subscribe').show(); $('#nlmail').val('') } else { alert("An error occurred"); } } }); } return false; }); /* Sand mail **********************************************************************/ $("#send-mail").click(function () { var name = $('input#name').val(); // get the value of the input field var error = false; if (name == "" || name == " ") { $('#err-name').show(500); $('#err-name').delay(4000); $('#err-name').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } var emailCompare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input var email = $('input#email').val().toLowerCase(); // get the value of the input field if (email == "" || email == " " || !emailCompare.test(email)) { $('#err-email').show(500); $('#err-email').delay(4000); $('#err-email').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } var comment = $('textarea#comment').val(); // get the value of the input field if (comment == "" || comment == " ") { $('#err-comment').show(500); $('#err-comment').delay(4000); $('#err-comment').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } if (error == false) { var dataString = $('#contact-form').serialize(); // Collect data from form $.ajax({ type: "POST", url: $('#contact-form').attr('action'), data: dataString, timeout: 6000, error: function (request, error) { }, success: function (response) { response = $.parseJSON(response); if (response.success) { $('#successSend').show(); $("#name").val(''); $("#email").val(''); $("#comment").val(''); } else { $('#errorSend').show(); } } }); return false; } return false; // stops user browser being directed to the php file }); //Function for show or hide portfolio desctiption. $.fn.showHide = function (options) { var defaults = { speed: 1000, easing: '', changeText: 0, showText: 'Show', hideText: 'Hide' }; var options = $.extend(defaults, options); $(this).click(function () { $('.toggleDiv').slideUp(options.speed, options.easing); var toggleClick = $(this); var toggleDiv = $(this).attr('rel'); $(toggleDiv).slideToggle(options.speed, options.easing, function () { if (options.changeText == 1) { $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText); } }); return false; }); }; //Initial Show/Hide portfolio element. $('div.toggleDiv').hide(); /************************ Animate elements *************************/ //Animate thumbnails jQuery('.thumbnail').one('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //Animate triangles jQuery('.triangle').bind('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //animate first team member jQuery('#first-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#first-person').addClass("animated pulse"); } else { jQuery('#first-person').removeClass("animated pulse"); } }); //animate sectond team member jQuery('#second-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#second-person').addClass("animated pulse"); } else { jQuery('#second-person').removeClass("animated pulse"); } }); //animate thrid team member jQuery('#third-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#third-person').addClass("animated pulse"); } else { jQuery('#third-person').removeClass("animated pulse"); } }); //Animate price columns jQuery('.price-column, .testimonial').bind('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //Animate contact form jQuery('.contact-form').bind('inview', function (event, visible) { if (visible == true) { jQuery('.contact-form').addClass("animated bounceIn"); } else { jQuery('.contact-form').removeClass("animated bounceIn"); } }); //Animate skill bars jQuery('.skills > li > span').one('inview', function (event, visible) { if (visible == true) { jQuery(this).each(function () { jQuery(this).animate({ width: jQuery(this).attr('data-width') }, 3000); }); } }); //initialize pluging $("a[rel^='prettyPhoto']").prettyPhoto(); //contact form function enviainfocurso() { $.ajax({ type: "POST", url: "php/phpscripts/infocurso.php", async: true, data: $('form.informacao').serialize(), }); alert('Entraremos em breve em contato com você'); } //analytics (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-62932901-1', 'auto'); ga('send', 'pageview'); }); // end ready() $(window).load(function () { function filterPath(string) { return string.replace(/^\//, '').replace(/(index|default).[a-zA-Z]{3,4}$/, '').replace(/\/$/, ''); } $('a[href*=#]').each(function () { if (filterPath(location.pathname) == filterPath(this.pathname) && location.hostname == this.hostname && this.hash.replace(/#/, '')) { var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) + ']'); var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false; if ( $target ) { $(this).click(function (e) { e.preventDefault(); //Hack collapse top navigation after clicking // topMenu.parent().attr('style', 'height:0px').removeClass('in'); //Close navigation $('.navbar .btn-navbar').addClass('collapsed'); var targetOffset = $target.offset().top - 63; $('html, body').animate({ scrollTop: targetOffset }, 800); return false; }); } } }); }); //Initialize google map for contact setion with your location. function i
) { if( $("#map-canvas").length ) { var lat = '-8.0618743';//-8.055967'; //Set your latitude. var lon = '-34.8734548';//'-34.896303'; //Set your longitude. var centerLon = lon - 0.0105; var myOptions = { scrollwheel: false, draggable: false, disableDefaultUI: true, center: new google.maps.LatLng(lat, centerLon), zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; //Bind map to elemet with id map-canvas var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions); var marker = new google.maps.Marker({ map: map, position: new google.maps.LatLng(lat, lon), }); //var infowindow = new google.maps.InfoWindow(); //google.maps.event.addListener(marker, 'click', function () { // infowindow.open(map, marker); //}); // infowindow.open(map, marker); } }
nitializeMap(
identifier_name
app.js
'use strict'; jQuery(document).ready(function ($) { var lastId, topMenu = $("#top-navigation"), topMenuHeight = topMenu.outerHeight(), // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function () { var item = $($(this).attr("href")); if (item.length) { return item; } }); //Get width of container var containerWidth = $('.section .container').width(); //Resize animated triangle $(".triangle").css({ "border-left": containerWidth / 2 + 'px outset transparent', "border-right": containerWidth / 2 + 'px outset transparent' }); //resize $(window).resize(function () { containerWidth = $('.container').width(); $(".triangle").css({ "border-left": containerWidth / 2 + 'px outset transparent', "border-right": containerWidth / 2 + 'px outset transparent' }); }); //mask $('.has-mask').each( function() { var $this = $( this ), mask = $this.data( 'aria-mask' ); $this.mask( mask ); }); //Initialize header slider. $('#da-slider').cslider(); //Initial mixitup, used for animated filtering portgolio. $('#portfolio-grid').mixitup({ 'onMixStart': function (config) { $('div.toggleDiv').hide(); } }); //Initial Out clients slider in client section $('#clint-slider').bxSlider({ pager: false, minSlides: 1, maxSlides: 5, moveSlides: 2, slideWidth: 210, slideMargin: 25, prevSelector: $('#client-prev'), nextSelector: $('#client-next'), prevText: '<i class="icon-left-open"></i>', nextText: '<i class="icon-right-open"></i>' }); $('input, textarea').placeholder(); // Bind to scroll $(window).scroll(function () { //Display or hide scroll to top button if ($(this).scrollTop() > 100) { $('.scrollup').fadeIn(); } else { $('.scrollup').fadeOut(); } if ($(this).scrollTop() > 100) { $('.navbar').addClass('navbar-fixed-top animated fadeInDown'); } else { $('.navbar').removeClass('navbar-fixed-top animated fadeInDown'); } // Get container scroll position var fromTop = $(this).scrollTop() + topMenuHeight + 10; // Get id of current scroll item var cur = scrollItems.map(function () { if ($(this).offset().top < fromTop) return this; }); // Get the id of the current element cur = cur[cur.length - 1]; var id = cur && cur.length ? cur[0].id : ""; if (lastId !== id) { lastId = id; // Set/remove active class menuItems .parent().removeClass("active") .end().filter("[href=#" + id + "]").parent().addClass("active"); } }); /* Function for scroliing to top ************************************/ $('.scrollup').click(function () { $("html, body").animate({ scrollTop: 0 }, 600); return false; }); /* Sand newsletter **********************************************************************/ $('#subscribe').click(function () { var error = false; var emailCompare = /^([a-z0-9_.-]+)@([0-9a-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input var email = $('input#nlmail').val().toLowerCase(); // get the value of the input field if (email == "" || email == " " || !emailCompare.test(email)) { $('#err-subscribe').show(500); $('#err-subscribe').delay(4000); $('#err-subscribe').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } if (error === false) { $.ajax({ type: 'POST', url: 'php/newsletter.php', data: { email: $('#nlmail').val() }, error: function (request, error) { alert("An error occurred"); }, success: function (response) { if (response == 'OK') { $('#success-subscribe').show(); $('#nlmail').val('') } else { alert("An error occurred"); } } }); } return false; }); /* Sand mail **********************************************************************/ $("#send-mail").click(function () { var name = $('input#name').val(); // get the value of the input field var error = false; if (name == "" || name == " ") { $('#err-name').show(500); $('#err-name').delay(4000); $('#err-name').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } var emailCompare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input var email = $('input#email').val().toLowerCase(); // get the value of the input field if (email == "" || email == " " || !emailCompare.test(email)) { $('#err-email').show(500); $('#err-email').delay(4000); $('#err-email').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } var comment = $('textarea#comment').val(); // get the value of the input field if (comment == "" || comment == " ") { $('#err-comment').show(500); $('#err-comment').delay(4000); $('#err-comment').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } if (error == false) { var dataString = $('#contact-form').serialize(); // Collect data from form $.ajax({ type: "POST", url: $('#contact-form').attr('action'), data: dataString, timeout: 6000, error: function (request, error) { }, success: function (response) { response = $.parseJSON(response); if (response.success) { $('#successSend').show(); $("#name").val(''); $("#email").val(''); $("#comment").val(''); } else { $('#errorSend').show(); } } }); return false; } return false; // stops user browser being directed to the php file }); //Function for show or hide portfolio desctiption. $.fn.showHide = function (options) { var defaults = { speed: 1000, easing: '', changeText: 0, showText: 'Show', hideText: 'Hide' }; var options = $.extend(defaults, options); $(this).click(function () { $('.toggleDiv').slideUp(options.speed, options.easing); var toggleClick = $(this); var toggleDiv = $(this).attr('rel'); $(toggleDiv).slideToggle(options.speed, options.easing, function () { if (options.changeText == 1) { $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText); } }); return false; }); }; //Initial Show/Hide portfolio element. $('div.toggleDiv').hide(); /************************ Animate elements *************************/ //Animate thumbnails jQuery('.thumbnail').one('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //Animate triangles jQuery('.triangle').bind('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //animate first team member jQuery('#first-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#first-person').addClass("animated pulse"); } else { jQuery('#first-person').removeClass("animated pulse"); } }); //animate sectond team member jQuery('#second-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#second-person').addClass("animated pulse"); } else { jQuery('#second-person').removeClass("animated pulse"); } }); //animate thrid team member jQuery('#third-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#third-person').addClass("animated pulse"); } else { jQuery('#third-person').removeClass("animated pulse"); } }); //Animate price columns jQuery('.price-column, .testimonial').bind('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //Animate contact form jQuery('.contact-form').bind('inview', function (event, visible) { if (visible == true) { jQuery('.contact-form').addClass("animated bounceIn"); } else { jQuery('.contact-form').removeClass("animated bounceIn"); } }); //Animate skill bars jQuery('.skills > li > span').one('inview', function (event, visible) { if (visible == true) { jQuery(this).each(function () { jQuery(this).animate({ width: jQuery(this).attr('data-width') }, 3000); }); } }); //initialize pluging $("a[rel^='prettyPhoto']").prettyPhoto(); //contact form function enviainfocurso()
//analytics (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-62932901-1', 'auto'); ga('send', 'pageview'); }); // end ready() $(window).load(function () { function filterPath(string) { return string.replace(/^\//, '').replace(/(index|default).[a-zA-Z]{3,4}$/, '').replace(/\/$/, ''); } $('a[href*=#]').each(function () { if (filterPath(location.pathname) == filterPath(this.pathname) && location.hostname == this.hostname && this.hash.replace(/#/, '')) { var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) + ']'); var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false; if ( $target ) { $(this).click(function (e) { e.preventDefault(); //Hack collapse top navigation after clicking // topMenu.parent().attr('style', 'height:0px').removeClass('in'); //Close navigation $('.navbar .btn-navbar').addClass('collapsed'); var targetOffset = $target.offset().top - 63; $('html, body').animate({ scrollTop: targetOffset }, 800); return false; }); } } }); }); //Initialize google map for contact setion with your location. function initializeMap() { if( $("#map-canvas").length ) { var lat = '-8.0618743';//-8.055967'; //Set your latitude. var lon = '-34.8734548';//'-34.896303'; //Set your longitude. var centerLon = lon - 0.0105; var myOptions = { scrollwheel: false, draggable: false, disableDefaultUI: true, center: new google.maps.LatLng(lat, centerLon), zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; //Bind map to elemet with id map-canvas var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions); var marker = new google.maps.Marker({ map: map, position: new google.maps.LatLng(lat, lon), }); //var infowindow = new google.maps.InfoWindow(); //google.maps.event.addListener(marker, 'click', function () { // infowindow.open(map, marker); //}); // infowindow.open(map, marker); } }
{ $.ajax({ type: "POST", url: "php/phpscripts/infocurso.php", async: true, data: $('form.informacao').serialize(), }); alert('Entraremos em breve em contato com você'); }
identifier_body
app.js
'use strict'; jQuery(document).ready(function ($) { var lastId, topMenu = $("#top-navigation"), topMenuHeight = topMenu.outerHeight(), // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function () { var item = $($(this).attr("href")); if (item.length) { return item; } }); //Get width of container var containerWidth = $('.section .container').width(); //Resize animated triangle $(".triangle").css({ "border-left": containerWidth / 2 + 'px outset transparent', "border-right": containerWidth / 2 + 'px outset transparent' }); //resize $(window).resize(function () { containerWidth = $('.container').width(); $(".triangle").css({ "border-left": containerWidth / 2 + 'px outset transparent', "border-right": containerWidth / 2 + 'px outset transparent' }); }); //mask $('.has-mask').each( function() { var $this = $( this ), mask = $this.data( 'aria-mask' ); $this.mask( mask ); }); //Initialize header slider. $('#da-slider').cslider(); //Initial mixitup, used for animated filtering portgolio. $('#portfolio-grid').mixitup({ 'onMixStart': function (config) { $('div.toggleDiv').hide(); } }); //Initial Out clients slider in client section $('#clint-slider').bxSlider({ pager: false, minSlides: 1, maxSlides: 5, moveSlides: 2, slideWidth: 210, slideMargin: 25, prevSelector: $('#client-prev'), nextSelector: $('#client-next'), prevText: '<i class="icon-left-open"></i>', nextText: '<i class="icon-right-open"></i>' }); $('input, textarea').placeholder(); // Bind to scroll $(window).scroll(function () { //Display or hide scroll to top button if ($(this).scrollTop() > 100) { $('.scrollup').fadeIn(); } else { $('.scrollup').fadeOut(); } if ($(this).scrollTop() > 100) { $('.navbar').addClass('navbar-fixed-top animated fadeInDown'); } else { $('.navbar').removeClass('navbar-fixed-top animated fadeInDown'); } // Get container scroll position var fromTop = $(this).scrollTop() + topMenuHeight + 10; // Get id of current scroll item var cur = scrollItems.map(function () { if ($(this).offset().top < fromTop) return this; }); // Get the id of the current element cur = cur[cur.length - 1]; var id = cur && cur.length ? cur[0].id : ""; if (lastId !== id) { lastId = id; // Set/remove active class menuItems .parent().removeClass("active") .end().filter("[href=#" + id + "]").parent().addClass("active"); } }); /* Function for scroliing to top ************************************/ $('.scrollup').click(function () { $("html, body").animate({ scrollTop: 0 }, 600); return false; }); /* Sand newsletter **********************************************************************/ $('#subscribe').click(function () { var error = false; var emailCompare = /^([a-z0-9_.-]+)@([0-9a-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input var email = $('input#nlmail').val().toLowerCase(); // get the value of the input field if (email == "" || email == " " || !emailCompare.test(email)) { $('#err-subscribe').show(500); $('#err-subscribe').delay(4000); $('#err-subscribe').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } if (error === false) { $.ajax({ type: 'POST', url: 'php/newsletter.php', data: { email: $('#nlmail').val() }, error: function (request, error) { alert("An error occurred"); }, success: function (response) { if (response == 'OK') { $('#success-subscribe').show(); $('#nlmail').val('') } else { alert("An error occurred"); } } }); } return false; }); /* Sand mail **********************************************************************/ $("#send-mail").click(function () { var name = $('input#name').val(); // get the value of the input field var error = false; if (name == "" || name == " ") { $('#err-name').show(500); $('#err-name').delay(4000); $('#err-name').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } var emailCompare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input var email = $('input#email').val().toLowerCase(); // get the value of the input field if (email == "" || email == " " || !emailCompare.test(email)) { $('#err-email').show(500); $('#err-email').delay(4000); $('#err-email').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } var comment = $('textarea#comment').val(); // get the value of the input field if (comment == "" || comment == " ") { $('#err-comment').show(500); $('#err-comment').delay(4000); $('#err-comment').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } if (error == false) { var dataString = $('#contact-form').serialize(); // Collect data from form $.ajax({ type: "POST", url: $('#contact-form').attr('action'), data: dataString, timeout: 6000, error: function (request, error) { }, success: function (response) { response = $.parseJSON(response); if (response.success) { $('#successSend').show(); $("#name").val(''); $("#email").val(''); $("#comment").val(''); } else { $('#errorSend').show(); } } }); return false; } return false; // stops user browser being directed to the php file }); //Function for show or hide portfolio desctiption. $.fn.showHide = function (options) { var defaults = { speed: 1000, easing: '', changeText: 0, showText: 'Show',
var toggleClick = $(this); var toggleDiv = $(this).attr('rel'); $(toggleDiv).slideToggle(options.speed, options.easing, function () { if (options.changeText == 1) { $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText); } }); return false; }); }; //Initial Show/Hide portfolio element. $('div.toggleDiv').hide(); /************************ Animate elements *************************/ //Animate thumbnails jQuery('.thumbnail').one('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //Animate triangles jQuery('.triangle').bind('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //animate first team member jQuery('#first-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#first-person').addClass("animated pulse"); } else { jQuery('#first-person').removeClass("animated pulse"); } }); //animate sectond team member jQuery('#second-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#second-person').addClass("animated pulse"); } else { jQuery('#second-person').removeClass("animated pulse"); } }); //animate thrid team member jQuery('#third-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#third-person').addClass("animated pulse"); } else { jQuery('#third-person').removeClass("animated pulse"); } }); //Animate price columns jQuery('.price-column, .testimonial').bind('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //Animate contact form jQuery('.contact-form').bind('inview', function (event, visible) { if (visible == true) { jQuery('.contact-form').addClass("animated bounceIn"); } else { jQuery('.contact-form').removeClass("animated bounceIn"); } }); //Animate skill bars jQuery('.skills > li > span').one('inview', function (event, visible) { if (visible == true) { jQuery(this).each(function () { jQuery(this).animate({ width: jQuery(this).attr('data-width') }, 3000); }); } }); //initialize pluging $("a[rel^='prettyPhoto']").prettyPhoto(); //contact form function enviainfocurso() { $.ajax({ type: "POST", url: "php/phpscripts/infocurso.php", async: true, data: $('form.informacao').serialize(), }); alert('Entraremos em breve em contato com você'); } //analytics (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-62932901-1', 'auto'); ga('send', 'pageview'); }); // end ready() $(window).load(function () { function filterPath(string) { return string.replace(/^\//, '').replace(/(index|default).[a-zA-Z]{3,4}$/, '').replace(/\/$/, ''); } $('a[href*=#]').each(function () { if (filterPath(location.pathname) == filterPath(this.pathname) && location.hostname == this.hostname && this.hash.replace(/#/, '')) { var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) + ']'); var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false; if ( $target ) { $(this).click(function (e) { e.preventDefault(); //Hack collapse top navigation after clicking // topMenu.parent().attr('style', 'height:0px').removeClass('in'); //Close navigation $('.navbar .btn-navbar').addClass('collapsed'); var targetOffset = $target.offset().top - 63; $('html, body').animate({ scrollTop: targetOffset }, 800); return false; }); } } }); }); //Initialize google map for contact setion with your location. function initializeMap() { if( $("#map-canvas").length ) { var lat = '-8.0618743';//-8.055967'; //Set your latitude. var lon = '-34.8734548';//'-34.896303'; //Set your longitude. var centerLon = lon - 0.0105; var myOptions = { scrollwheel: false, draggable: false, disableDefaultUI: true, center: new google.maps.LatLng(lat, centerLon), zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; //Bind map to elemet with id map-canvas var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions); var marker = new google.maps.Marker({ map: map, position: new google.maps.LatLng(lat, lon), }); //var infowindow = new google.maps.InfoWindow(); //google.maps.event.addListener(marker, 'click', function () { // infowindow.open(map, marker); //}); // infowindow.open(map, marker); } }
hideText: 'Hide' }; var options = $.extend(defaults, options); $(this).click(function () { $('.toggleDiv').slideUp(options.speed, options.easing);
random_line_split
app.js
'use strict'; jQuery(document).ready(function ($) { var lastId, topMenu = $("#top-navigation"), topMenuHeight = topMenu.outerHeight(), // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function () { var item = $($(this).attr("href")); if (item.length) { return item; } }); //Get width of container var containerWidth = $('.section .container').width(); //Resize animated triangle $(".triangle").css({ "border-left": containerWidth / 2 + 'px outset transparent', "border-right": containerWidth / 2 + 'px outset transparent' }); //resize $(window).resize(function () { containerWidth = $('.container').width(); $(".triangle").css({ "border-left": containerWidth / 2 + 'px outset transparent', "border-right": containerWidth / 2 + 'px outset transparent' }); }); //mask $('.has-mask').each( function() { var $this = $( this ), mask = $this.data( 'aria-mask' ); $this.mask( mask ); }); //Initialize header slider. $('#da-slider').cslider(); //Initial mixitup, used for animated filtering portgolio. $('#portfolio-grid').mixitup({ 'onMixStart': function (config) { $('div.toggleDiv').hide(); } }); //Initial Out clients slider in client section $('#clint-slider').bxSlider({ pager: false, minSlides: 1, maxSlides: 5, moveSlides: 2, slideWidth: 210, slideMargin: 25, prevSelector: $('#client-prev'), nextSelector: $('#client-next'), prevText: '<i class="icon-left-open"></i>', nextText: '<i class="icon-right-open"></i>' }); $('input, textarea').placeholder(); // Bind to scroll $(window).scroll(function () { //Display or hide scroll to top button if ($(this).scrollTop() > 100) { $('.scrollup').fadeIn(); } else { $('.scrollup').fadeOut(); } if ($(this).scrollTop() > 100) { $('.navbar').addClass('navbar-fixed-top animated fadeInDown'); } else { $('.navbar').removeClass('navbar-fixed-top animated fadeInDown'); } // Get container scroll position var fromTop = $(this).scrollTop() + topMenuHeight + 10; // Get id of current scroll item var cur = scrollItems.map(function () { if ($(this).offset().top < fromTop) return this; }); // Get the id of the current element cur = cur[cur.length - 1]; var id = cur && cur.length ? cur[0].id : ""; if (lastId !== id) { lastId = id; // Set/remove active class menuItems .parent().removeClass("active") .end().filter("[href=#" + id + "]").parent().addClass("active"); } }); /* Function for scroliing to top ************************************/ $('.scrollup').click(function () { $("html, body").animate({ scrollTop: 0 }, 600); return false; }); /* Sand newsletter **********************************************************************/ $('#subscribe').click(function () { var error = false; var emailCompare = /^([a-z0-9_.-]+)@([0-9a-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input var email = $('input#nlmail').val().toLowerCase(); // get the value of the input field if (email == "" || email == " " || !emailCompare.test(email)) { $('#err-subscribe').show(500); $('#err-subscribe').delay(4000); $('#err-subscribe').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } if (error === false) { $.ajax({ type: 'POST', url: 'php/newsletter.php', data: { email: $('#nlmail').val() }, error: function (request, error) { alert("An error occurred"); }, success: function (response) { if (response == 'OK') { $('#success-subscribe').show(); $('#nlmail').val('') } else { alert("An error occurred"); } } }); } return false; }); /* Sand mail **********************************************************************/ $("#send-mail").click(function () { var name = $('input#name').val(); // get the value of the input field var error = false; if (name == "" || name == " ") { $('#err-name').show(500); $('#err-name').delay(4000); $('#err-name').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } var emailCompare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input var email = $('input#email').val().toLowerCase(); // get the value of the input field if (email == "" || email == " " || !emailCompare.test(email)) { $('#err-email').show(500); $('#err-email').delay(4000); $('#err-email').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } var comment = $('textarea#comment').val(); // get the value of the input field if (comment == "" || comment == " ") { $('#err-comment').show(500); $('#err-comment').delay(4000); $('#err-comment').animate({ height: 'toggle' }, 500, function () { // Animation complete. }); error = true; // change the error state to true } if (error == false) { var dataString = $('#contact-form').serialize(); // Collect data from form $.ajax({ type: "POST", url: $('#contact-form').attr('action'), data: dataString, timeout: 6000, error: function (request, error) { }, success: function (response) { response = $.parseJSON(response); if (response.success) { $('#successSend').show(); $("#name").val(''); $("#email").val(''); $("#comment").val(''); } else { $('#errorSend').show(); } } }); return false; } return false; // stops user browser being directed to the php file }); //Function for show or hide portfolio desctiption. $.fn.showHide = function (options) { var defaults = { speed: 1000, easing: '', changeText: 0, showText: 'Show', hideText: 'Hide' }; var options = $.extend(defaults, options); $(this).click(function () { $('.toggleDiv').slideUp(options.speed, options.easing); var toggleClick = $(this); var toggleDiv = $(this).attr('rel'); $(toggleDiv).slideToggle(options.speed, options.easing, function () { if (options.changeText == 1) { $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText); } }); return false; }); }; //Initial Show/Hide portfolio element. $('div.toggleDiv').hide(); /************************ Animate elements *************************/ //Animate thumbnails jQuery('.thumbnail').one('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //Animate triangles jQuery('.triangle').bind('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //animate first team member jQuery('#first-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#first-person').addClass("animated pulse"); } else { jQuery('#first-person').removeClass("animated pulse"); } }); //animate sectond team member jQuery('#second-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#second-person').addClass("animated pulse"); } else { jQuery('#second-person').removeClass("animated pulse"); } }); //animate thrid team member jQuery('#third-person').bind('inview', function (event, visible) { if (visible == true) { jQuery('#third-person').addClass("animated pulse"); } else { jQuery('#third-person').removeClass("animated pulse"); } }); //Animate price columns jQuery('.price-column, .testimonial').bind('inview', function (event, visible) { if (visible == true) { jQuery(this).addClass("animated fadeInDown"); } else { jQuery(this).removeClass("animated fadeInDown"); } }); //Animate contact form jQuery('.contact-form').bind('inview', function (event, visible) { if (visible == true) { jQuery('.contact-form').addClass("animated bounceIn"); } else { jQuery('.contact-form').removeClass("animated bounceIn"); } }); //Animate skill bars jQuery('.skills > li > span').one('inview', function (event, visible) { if (visible == true) { jQuery(this).each(function () { jQuery(this).animate({ width: jQuery(this).attr('data-width') }, 3000); }); } }); //initialize pluging $("a[rel^='prettyPhoto']").prettyPhoto(); //contact form function enviainfocurso() { $.ajax({ type: "POST", url: "php/phpscripts/infocurso.php", async: true, data: $('form.informacao').serialize(), }); alert('Entraremos em breve em contato com você'); } //analytics (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-62932901-1', 'auto'); ga('send', 'pageview'); }); // end ready() $(window).load(function () { function filterPath(string) { return string.replace(/^\//, '').replace(/(index|default).[a-zA-Z]{3,4}$/, '').replace(/\/$/, ''); } $('a[href*=#]').each(function () { if (filterPath(location.pathname) == filterPath(this.pathname) && location.hostname == this.hostname && this.hash.replace(/#/, '')) {
}); }); //Initialize google map for contact setion with your location. function initializeMap() { if( $("#map-canvas").length ) { var lat = '-8.0618743';//-8.055967'; //Set your latitude. var lon = '-34.8734548';//'-34.896303'; //Set your longitude. var centerLon = lon - 0.0105; var myOptions = { scrollwheel: false, draggable: false, disableDefaultUI: true, center: new google.maps.LatLng(lat, centerLon), zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; //Bind map to elemet with id map-canvas var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions); var marker = new google.maps.Marker({ map: map, position: new google.maps.LatLng(lat, lon), }); //var infowindow = new google.maps.InfoWindow(); //google.maps.event.addListener(marker, 'click', function () { // infowindow.open(map, marker); //}); // infowindow.open(map, marker); } }
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) + ']'); var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false; if ( $target ) { $(this).click(function (e) { e.preventDefault(); //Hack collapse top navigation after clicking // topMenu.parent().attr('style', 'height:0px').removeClass('in'); //Close navigation $('.navbar .btn-navbar').addClass('collapsed'); var targetOffset = $target.offset().top - 63; $('html, body').animate({ scrollTop: targetOffset }, 800); return false; }); } }
conditional_block
receta-medica.component.ts
import { HTMLComponent } from '../../model/html-component.class'; export class RecetaMedicaComponent extends HTMLComponent { template = `
</div> <table class="table table-bordered"> <thead> <tr> <th>Medicamento</th> <th>Presentación</th> <th>Cantidad</th> <th>Dosis diaria</th> <th>Diagnóstico</th> <th>Observaciones</th> </tr> </thead> <tbody> {{#each registro.valor.medicamentos}} <tr> <td> {{generico.term}} </td> <td> {{ unidades }} {{presentacion.term }}(s) </td> <td> {{ cantidad }} envase(s) </td> <td> {{#if dosisDiaria.cantidad }} {{ dosisDiaria.cantidad }} {{presentacion.term }}(s) por {{ dosisDiaria.dias }} días {{/if}} </td> <td> {{ diagnostico }} </td> <td> {{#if tratamientoProlongado }} Tratamiento prolongado | {{/if}} {{ tipoReceta }} </td> </tr> {{/each}} </tbody> </table> `; constructor(private prestacion, private registro, private params, private depth) { super(); } async process() { this.data = { registro: this.registro }; } }
<div class="nivel-1"> <p> {{#if registro.valor.medicamentos}}<b>RECETA MÉDICA</b>{{/if}} </p>
random_line_split
receta-medica.component.ts
import { HTMLComponent } from '../../model/html-component.class'; export class RecetaMedicaComponent extends HTMLComponent { template = ` <div class="nivel-1"> <p> {{#if registro.valor.medicamentos}}<b>RECETA MÉDICA</b>{{/if}} </p> </div> <table class="table table-bordered"> <thead> <tr> <th>Medicamento</th> <th>Presentación</th> <th>Cantidad</th> <th>Dosis diaria</th> <th>Diagnóstico</th> <th>Observaciones</th> </tr> </thead> <tbody> {{#each registro.valor.medicamentos}} <tr> <td> {{generico.term}} </td> <td> {{ unidades }} {{presentacion.term }}(s) </td> <td> {{ cantidad }} envase(s) </td> <td> {{#if dosisDiaria.cantidad }} {{ dosisDiaria.cantidad }} {{presentacion.term }}(s) por {{ dosisDiaria.dias }} días {{/if}} </td> <td> {{ diagnostico }} </td> <td> {{#if tratamientoProlongado }} Tratamiento prolongado | {{/if}} {{ tipoReceta }} </td> </tr> {{/each}} </tbody> </table> `; cons
vate prestacion, private registro, private params, private depth) { super(); } async process() { this.data = { registro: this.registro }; } }
tructor(pri
identifier_name
receta-medica.component.ts
import { HTMLComponent } from '../../model/html-component.class'; export class RecetaMedicaComponent extends HTMLComponent { template = ` <div class="nivel-1"> <p> {{#if registro.valor.medicamentos}}<b>RECETA MÉDICA</b>{{/if}} </p> </div> <table class="table table-bordered"> <thead> <tr> <th>Medicamento</th> <th>Presentación</th> <th>Cantidad</th> <th>Dosis diaria</th> <th>Diagnóstico</th> <th>Observaciones</th> </tr> </thead> <tbody> {{#each registro.valor.medicamentos}} <tr> <td> {{generico.term}} </td> <td> {{ unidades }} {{presentacion.term }}(s) </td> <td> {{ cantidad }} envase(s) </td> <td> {{#if dosisDiaria.cantidad }} {{ dosisDiaria.cantidad }} {{presentacion.term }}(s) por {{ dosisDiaria.dias }} días {{/if}} </td> <td> {{ diagnostico }} </td> <td> {{#if tratamientoProlongado }} Tratamiento prolongado | {{/if}} {{ tipoReceta }} </td> </tr> {{/each}} </tbody> </table> `; constructor(private prestacion, private registro, private params, private depth) { super(); } async process() {
this.data = { registro: this.registro }; } }
identifier_body
conf.py
# -*- coding: utf-8 -*- # # dolphintools documentation build configuration file, created by # sphinx-quickstart on Mon Oct 12 22:39:14 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'dolphintools' copyright = u'2015, Alper Kucukural' author = u'Alper Kucukural' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0.0' # The full version, including alpha/beta/rc tags. release = '1.0.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme
#html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'dolphintoolsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'dolphintools.tex', u'dolphintools Documentation', u'Alper Kucukural', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'dolphintools', u'dolphintools Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'dolphintools', u'dolphintools Documentation', author, 'dolphintools', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
# further. For a list of options available for each theme, see the # documentation.
random_line_split