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
views.py
from rest_framework import generics, permissions, views, response,status from .models import Account from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \ UpdateAccountSerializer, AccountRetrieveSerializer # Create your views here. class AccountCreateView(generics.CreateAPIView): queryset = Account.objects.all() serializer_class = AccountCreateSerializer permission_classes = [permissions.AllowAny] class AccountListView(generics.ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [permissions.IsAuthenticated] class
(generics.RetrieveAPIView): queryset = Account.objects.all() serializer_class = AccountRetrieveSerializer class UpdateAccountView(generics.UpdateAPIView): queryset = Account.objects.all() serializer_class = UpdateAccountSerializer # permission_classes = [permissions.IsAuthenticated] class AccountAuthenticationView(views.APIView): queryset = Account.objects.all() serializer_class = AuthenticateSerializer def post(self, request): data = request.data serializer = AuthenticateSerializer(data=data) if serializer.is_valid(raise_exception=True): new_date = serializer.data return response.Response(new_date,status=status.HTTP_200_OK) return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
AccountRetrieveView
identifier_name
views.py
from rest_framework import generics, permissions, views, response,status from .models import Account from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \ UpdateAccountSerializer, AccountRetrieveSerializer # Create your views here. class AccountCreateView(generics.CreateAPIView): queryset = Account.objects.all() serializer_class = AccountCreateSerializer permission_classes = [permissions.AllowAny] class AccountListView(generics.ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [permissions.IsAuthenticated] class AccountRetrieveView(generics.RetrieveAPIView): queryset = Account.objects.all() serializer_class = AccountRetrieveSerializer class UpdateAccountView(generics.UpdateAPIView): queryset = Account.objects.all() serializer_class = UpdateAccountSerializer # permission_classes = [permissions.IsAuthenticated] class AccountAuthenticationView(views.APIView):
queryset = Account.objects.all() serializer_class = AuthenticateSerializer def post(self, request): data = request.data serializer = AuthenticateSerializer(data=data) if serializer.is_valid(raise_exception=True): new_date = serializer.data return response.Response(new_date,status=status.HTTP_200_OK) return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
identifier_body
views.py
from rest_framework import generics, permissions, views, response,status from .models import Account from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \ UpdateAccountSerializer, AccountRetrieveSerializer # Create your views here. class AccountCreateView(generics.CreateAPIView): queryset = Account.objects.all() serializer_class = AccountCreateSerializer permission_classes = [permissions.AllowAny] class AccountListView(generics.ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [permissions.IsAuthenticated] class AccountRetrieveView(generics.RetrieveAPIView): queryset = Account.objects.all() serializer_class = AccountRetrieveSerializer class UpdateAccountView(generics.UpdateAPIView): queryset = Account.objects.all() serializer_class = UpdateAccountSerializer # permission_classes = [permissions.IsAuthenticated] class AccountAuthenticationView(views.APIView): queryset = Account.objects.all() serializer_class = AuthenticateSerializer def post(self, request): data = request.data serializer = AuthenticateSerializer(data=data) if serializer.is_valid(raise_exception=True):
return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
new_date = serializer.data return response.Response(new_date,status=status.HTTP_200_OK)
conditional_block
test_tfidf.py
import unittest from datetime import datetime import tempfile import os
from due.episode import Episode from due.event import Event from due.persistence import serialize, deserialize from due.models.tfidf import TfIdfAgent from due.models.dummy import DummyAgent class TestTfIdfAgent(unittest.TestCase): def test_save_load(self): agent = TfIdfAgent() agent.learn_episodes(_get_train_episodes()) saved_agent = agent.save() with tempfile.TemporaryDirectory() as temp_dir: path = os.path.join(temp_dir, 'serialized_tfidf_agent.due') serialize(saved_agent, path) loaded_agent = Agent.load(deserialize(path)) assert agent.parameters == loaded_agent.parameters assert agent._normalized_past_utterances == loaded_agent._normalized_past_utterances assert [e.save() for e in loaded_agent._past_episodes] == [e.save() for e in agent._past_episodes] expected_utterance = agent._process_utterance('aaa bbb ccc mario') loaded_utterance = loaded_agent._process_utterance('aaa bbb ccc mario') assert (agent._vectorizer.transform([expected_utterance]) != loaded_agent._vectorizer.transform([loaded_utterance])).nnz == 0 assert (agent._vectorized_past_utterances != loaded_agent._vectorized_past_utterances).nnz == 0 assert agent.utterance_callback(_get_test_episode())[0].payload, loaded_agent.utterance_callback(_get_test_episode())[0].payload def test_utterance_callback(self): agent = TfIdfAgent() agent.learn_episodes(_get_train_episodes()) result = agent.utterance_callback(_get_test_episode()) self.assertEqual(result[0].payload, 'bbb') def test_tfidf_agent(self): cb = TfIdfAgent() # Learn sample episode sample_episode, alice, bob = _sample_episode() cb.learn_episodes([sample_episode]) # Predict answer e2 = alice.start_episode(bob) alice.say("Hi!", e2) answer_events = cb.utterance_callback(e2) self.assertEqual(len(answer_events), 1) self.assertEqual(answer_events[0].payload, 'Hello') def test_agent_load(self): sample_episode, alice, bob = _sample_episode() cb = TfIdfAgent() cb.learn_episodes([sample_episode]) test_dir = tempfile.mkdtemp() test_path = os.path.join(test_dir, 'test_agent_load.pkl') serialize(cb.save(), test_path) loaded_cb = Agent.load(deserialize(test_path)) self.assertIsInstance(loaded_cb, TfIdfAgent) e2 = alice.start_episode(bob) alice.say("Hi!", e2) answer_events = loaded_cb.utterance_callback(e2) self.assertEqual(len(answer_events), 1) self.assertEqual(answer_events[0].payload, 'Hello') def _get_train_episodes(): result = [] e = Episode('a', 'b') e.events = [ Event(Event.Type.Utterance, datetime.now(), 'a', 'aaa'), Event(Event.Type.Utterance, datetime.now(), 'b', 'bbb'), Event(Event.Type.Utterance, datetime.now(), 'a', 'ccc'), Event(Event.Type.Utterance, datetime.now(), 'b', 'ddd') ] result.append(e) e = Episode('1', '2') e.events = [ Event(Event.Type.Utterance, datetime.now(), '1', '111'), Event(Event.Type.Utterance, datetime.now(), '2', '222'), Event(Event.Type.Utterance, datetime.now(), '1', '333'), Event(Event.Type.Utterance, datetime.now(), '2', '444') ] result.append(e) return result def _get_test_episode(): e = Episode('a', 'b') e.events = [ Event(Event.Type.Utterance, datetime.now(), 'a', 'aaa'), ] return e def _sample_episode(): alice = DummyAgent('alice') bob = DummyAgent('bob') result = alice.start_episode(bob) alice.say("Hi!", result) bob.say("Hello", result) alice.say("How are you?", result) bob.say("Good thanks, and you?", result) alice.say("All good", result) return result, alice, bob
from due.agent import Agent
random_line_split
test_tfidf.py
import unittest from datetime import datetime import tempfile import os from due.agent import Agent from due.episode import Episode from due.event import Event from due.persistence import serialize, deserialize from due.models.tfidf import TfIdfAgent from due.models.dummy import DummyAgent class TestTfIdfAgent(unittest.TestCase): def test_save_load(self): agent = TfIdfAgent() agent.learn_episodes(_get_train_episodes()) saved_agent = agent.save() with tempfile.TemporaryDirectory() as temp_dir: path = os.path.join(temp_dir, 'serialized_tfidf_agent.due') serialize(saved_agent, path) loaded_agent = Agent.load(deserialize(path)) assert agent.parameters == loaded_agent.parameters assert agent._normalized_past_utterances == loaded_agent._normalized_past_utterances assert [e.save() for e in loaded_agent._past_episodes] == [e.save() for e in agent._past_episodes] expected_utterance = agent._process_utterance('aaa bbb ccc mario') loaded_utterance = loaded_agent._process_utterance('aaa bbb ccc mario') assert (agent._vectorizer.transform([expected_utterance]) != loaded_agent._vectorizer.transform([loaded_utterance])).nnz == 0 assert (agent._vectorized_past_utterances != loaded_agent._vectorized_past_utterances).nnz == 0 assert agent.utterance_callback(_get_test_episode())[0].payload, loaded_agent.utterance_callback(_get_test_episode())[0].payload def test_utterance_callback(self): agent = TfIdfAgent() agent.learn_episodes(_get_train_episodes()) result = agent.utterance_callback(_get_test_episode()) self.assertEqual(result[0].payload, 'bbb') def
(self): cb = TfIdfAgent() # Learn sample episode sample_episode, alice, bob = _sample_episode() cb.learn_episodes([sample_episode]) # Predict answer e2 = alice.start_episode(bob) alice.say("Hi!", e2) answer_events = cb.utterance_callback(e2) self.assertEqual(len(answer_events), 1) self.assertEqual(answer_events[0].payload, 'Hello') def test_agent_load(self): sample_episode, alice, bob = _sample_episode() cb = TfIdfAgent() cb.learn_episodes([sample_episode]) test_dir = tempfile.mkdtemp() test_path = os.path.join(test_dir, 'test_agent_load.pkl') serialize(cb.save(), test_path) loaded_cb = Agent.load(deserialize(test_path)) self.assertIsInstance(loaded_cb, TfIdfAgent) e2 = alice.start_episode(bob) alice.say("Hi!", e2) answer_events = loaded_cb.utterance_callback(e2) self.assertEqual(len(answer_events), 1) self.assertEqual(answer_events[0].payload, 'Hello') def _get_train_episodes(): result = [] e = Episode('a', 'b') e.events = [ Event(Event.Type.Utterance, datetime.now(), 'a', 'aaa'), Event(Event.Type.Utterance, datetime.now(), 'b', 'bbb'), Event(Event.Type.Utterance, datetime.now(), 'a', 'ccc'), Event(Event.Type.Utterance, datetime.now(), 'b', 'ddd') ] result.append(e) e = Episode('1', '2') e.events = [ Event(Event.Type.Utterance, datetime.now(), '1', '111'), Event(Event.Type.Utterance, datetime.now(), '2', '222'), Event(Event.Type.Utterance, datetime.now(), '1', '333'), Event(Event.Type.Utterance, datetime.now(), '2', '444') ] result.append(e) return result def _get_test_episode(): e = Episode('a', 'b') e.events = [ Event(Event.Type.Utterance, datetime.now(), 'a', 'aaa'), ] return e def _sample_episode(): alice = DummyAgent('alice') bob = DummyAgent('bob') result = alice.start_episode(bob) alice.say("Hi!", result) bob.say("Hello", result) alice.say("How are you?", result) bob.say("Good thanks, and you?", result) alice.say("All good", result) return result, alice, bob
test_tfidf_agent
identifier_name
test_tfidf.py
import unittest from datetime import datetime import tempfile import os from due.agent import Agent from due.episode import Episode from due.event import Event from due.persistence import serialize, deserialize from due.models.tfidf import TfIdfAgent from due.models.dummy import DummyAgent class TestTfIdfAgent(unittest.TestCase): def test_save_load(self):
def test_utterance_callback(self): agent = TfIdfAgent() agent.learn_episodes(_get_train_episodes()) result = agent.utterance_callback(_get_test_episode()) self.assertEqual(result[0].payload, 'bbb') def test_tfidf_agent(self): cb = TfIdfAgent() # Learn sample episode sample_episode, alice, bob = _sample_episode() cb.learn_episodes([sample_episode]) # Predict answer e2 = alice.start_episode(bob) alice.say("Hi!", e2) answer_events = cb.utterance_callback(e2) self.assertEqual(len(answer_events), 1) self.assertEqual(answer_events[0].payload, 'Hello') def test_agent_load(self): sample_episode, alice, bob = _sample_episode() cb = TfIdfAgent() cb.learn_episodes([sample_episode]) test_dir = tempfile.mkdtemp() test_path = os.path.join(test_dir, 'test_agent_load.pkl') serialize(cb.save(), test_path) loaded_cb = Agent.load(deserialize(test_path)) self.assertIsInstance(loaded_cb, TfIdfAgent) e2 = alice.start_episode(bob) alice.say("Hi!", e2) answer_events = loaded_cb.utterance_callback(e2) self.assertEqual(len(answer_events), 1) self.assertEqual(answer_events[0].payload, 'Hello') def _get_train_episodes(): result = [] e = Episode('a', 'b') e.events = [ Event(Event.Type.Utterance, datetime.now(), 'a', 'aaa'), Event(Event.Type.Utterance, datetime.now(), 'b', 'bbb'), Event(Event.Type.Utterance, datetime.now(), 'a', 'ccc'), Event(Event.Type.Utterance, datetime.now(), 'b', 'ddd') ] result.append(e) e = Episode('1', '2') e.events = [ Event(Event.Type.Utterance, datetime.now(), '1', '111'), Event(Event.Type.Utterance, datetime.now(), '2', '222'), Event(Event.Type.Utterance, datetime.now(), '1', '333'), Event(Event.Type.Utterance, datetime.now(), '2', '444') ] result.append(e) return result def _get_test_episode(): e = Episode('a', 'b') e.events = [ Event(Event.Type.Utterance, datetime.now(), 'a', 'aaa'), ] return e def _sample_episode(): alice = DummyAgent('alice') bob = DummyAgent('bob') result = alice.start_episode(bob) alice.say("Hi!", result) bob.say("Hello", result) alice.say("How are you?", result) bob.say("Good thanks, and you?", result) alice.say("All good", result) return result, alice, bob
agent = TfIdfAgent() agent.learn_episodes(_get_train_episodes()) saved_agent = agent.save() with tempfile.TemporaryDirectory() as temp_dir: path = os.path.join(temp_dir, 'serialized_tfidf_agent.due') serialize(saved_agent, path) loaded_agent = Agent.load(deserialize(path)) assert agent.parameters == loaded_agent.parameters assert agent._normalized_past_utterances == loaded_agent._normalized_past_utterances assert [e.save() for e in loaded_agent._past_episodes] == [e.save() for e in agent._past_episodes] expected_utterance = agent._process_utterance('aaa bbb ccc mario') loaded_utterance = loaded_agent._process_utterance('aaa bbb ccc mario') assert (agent._vectorizer.transform([expected_utterance]) != loaded_agent._vectorizer.transform([loaded_utterance])).nnz == 0 assert (agent._vectorized_past_utterances != loaded_agent._vectorized_past_utterances).nnz == 0 assert agent.utterance_callback(_get_test_episode())[0].payload, loaded_agent.utterance_callback(_get_test_episode())[0].payload
identifier_body
index.js
/** * Core dependencies. */ var path = require('path'); var dirname = path.dirname; /** * Create path. * * @param {String} pattern * @returns {Object} * @api private */ function createPattern(pattern) { return { pattern: pattern, included: true, served: true, watched: false }; } /** * Insert hydro into the loaded files. * * @param {Array} files * @api public */ function init(config) { var hydroConfig = config.hydro || {};
before.reverse().forEach(function(file) { config.files.unshift(createPattern(path.resolve(file))); }); } /** * Inject. */ init.$inject = [ 'config' ]; /** * Primary export. */ module.exports = { 'framework:hydro': [ 'factory', init ] };
var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js'; var before = hydroConfig.before || []; config.files.unshift(createPattern(__dirname + '/adapter.js')); config.files.unshift(createPattern(hydroJs));
random_line_split
index.js
/** * Core dependencies. */ var path = require('path'); var dirname = path.dirname; /** * Create path. * * @param {String} pattern * @returns {Object} * @api private */ function createPattern(pattern) { return { pattern: pattern, included: true, served: true, watched: false }; } /** * Insert hydro into the loaded files. * * @param {Array} files * @api public */ function init(config)
/** * Inject. */ init.$inject = [ 'config' ]; /** * Primary export. */ module.exports = { 'framework:hydro': [ 'factory', init ] };
{ var hydroConfig = config.hydro || {}; var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js'; var before = hydroConfig.before || []; config.files.unshift(createPattern(__dirname + '/adapter.js')); config.files.unshift(createPattern(hydroJs)); before.reverse().forEach(function(file) { config.files.unshift(createPattern(path.resolve(file))); }); }
identifier_body
index.js
/** * Core dependencies. */ var path = require('path'); var dirname = path.dirname; /** * Create path. * * @param {String} pattern * @returns {Object} * @api private */ function createPattern(pattern) { return { pattern: pattern, included: true, served: true, watched: false }; } /** * Insert hydro into the loaded files. * * @param {Array} files * @api public */ function
(config) { var hydroConfig = config.hydro || {}; var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js'; var before = hydroConfig.before || []; config.files.unshift(createPattern(__dirname + '/adapter.js')); config.files.unshift(createPattern(hydroJs)); before.reverse().forEach(function(file) { config.files.unshift(createPattern(path.resolve(file))); }); } /** * Inject. */ init.$inject = [ 'config' ]; /** * Primary export. */ module.exports = { 'framework:hydro': [ 'factory', init ] };
init
identifier_name
scatter-demo-basic.component.ts
import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef } from '@angular/core'; import { getThemes } from '@covalent/echarts/base'; import { ChartThemeSelectorService } from '../../../../../../utilities/chart-theme'; @Component({ selector: 'scatter-demo-basic', styleUrls: ['./scatter-demo-basic.component.scss'], templateUrl: './scatter-demo-basic.component.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class ScatterDemoBasicComponent implements OnInit { themes: string[] = getThemes(); selectedTheme: string; config: any = { tooltip: { show: true, }, legend: { right: 10, data: ['1990', '2015'], }, xAxis: [{ show: true }], yAxis: [{ show: true }], series: [ { name: '1990', data: [ [28604, 77, 17096869, 'Australia', 1990], [31163, 77.4, 27662440, 'Canada', 1990], [1516, 68, 1154605773, 'China', 1990], [13670, 74.7, 10582082, 'Cuba', 1990], [28599, 75, 4986705, 'Finland', 1990], [29476, 77.1, 56943299, 'France', 1990], [31476, 75.4, 78958237, 'Germany', 1990], [28666, 78.1, 254830, 'Iceland', 1990], [1777, 57.7, 870601776, 'India', 1990], [29550, 79.1, 122249285, 'Japan', 1990], [2076, 67.9, 20194354, 'North Korea', 1990], [12087, 72, 42972254, 'South Korea', 1990], [24021, 75.4, 3397534, 'New Zealand', 1990], [43296, 76.8, 4240375, 'Norway', 1990], [10088, 70.8, 38195258, 'Poland', 1990], [19349, 69.6, 147568552, 'Russia', 1990], [10670, 67.3, 53994605, 'Turkey', 1990], [26424, 75.7, 57110117, 'United Kingdom', 1990], [37062, 75.4, 252847810, 'United States', 1990], ], type: 'scatter', itemStyle: { opacity: 0.75, color: '#007373', }, symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; }, label: { show: true, formatter(param: any): any { return param.data[3]; }, position: 'top', }, }, { name: '2015', data: [ [44056, 81.8, 23968973, 'Australia', 2015], [43294, 81.7, 35939927, 'Canada', 2015], [13334, 76.9, 1376048943, 'China', 2015], [21291, 78.5, 11389562, 'Cuba', 2015], [38923, 80.8, 5503457, 'Finland', 2015], [37599, 81.9, 64395345, 'France', 2015], [44053, 81.1, 80688545, 'Germany', 2015], [42182, 82.8, 329425, 'Iceland', 2015], [5903, 66.8, 1311050527, 'India', 2015], [36162, 83.5, 126573481, 'Japan', 2015], [1390, 71.4, 25155317, 'North Korea', 2015], [34644, 80.7, 50293439, 'South Korea', 2015], [34186, 80.6, 4528526, 'New Zealand', 2015], [64304, 81.6, 5210967, 'Norway', 2015], [24787, 77.3, 38611794, 'Poland', 2015], [23038, 73.13, 143456918, 'Russia', 2015], [19360, 76.5, 78665830, 'Turkey', 2015], [38225, 81.4, 64715810, 'United Kingdom', 2015], [53354, 79.1, 321773631, 'United States', 2015], ], type: 'scatter', itemStyle: { opacity: 0.75, color: '#1B98C6', }, symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; }, label: { show: true, formatter(param: any): any { return param.data[3]; }, position: 'top', }, }, ], }; constructor(private _cdr: ChangeDetectorRef, public themeSelector: ChartThemeSelectorService) {} async
(): Promise<void> { this.selectedTheme = this.themeSelector.selected; this._cdr.markForCheck(); } selectChartTheme(theme: string): void { this.themeSelector.select(theme); } symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; } }
ngOnInit
identifier_name
scatter-demo-basic.component.ts
import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef } from '@angular/core'; import { getThemes } from '@covalent/echarts/base'; import { ChartThemeSelectorService } from '../../../../../../utilities/chart-theme'; @Component({ selector: 'scatter-demo-basic', styleUrls: ['./scatter-demo-basic.component.scss'], templateUrl: './scatter-demo-basic.component.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class ScatterDemoBasicComponent implements OnInit { themes: string[] = getThemes(); selectedTheme: string; config: any = { tooltip: { show: true, }, legend: { right: 10, data: ['1990', '2015'], }, xAxis: [{ show: true }], yAxis: [{ show: true }], series: [ { name: '1990', data: [ [28604, 77, 17096869, 'Australia', 1990], [31163, 77.4, 27662440, 'Canada', 1990], [1516, 68, 1154605773, 'China', 1990], [13670, 74.7, 10582082, 'Cuba', 1990], [28599, 75, 4986705, 'Finland', 1990], [29476, 77.1, 56943299, 'France', 1990], [31476, 75.4, 78958237, 'Germany', 1990], [28666, 78.1, 254830, 'Iceland', 1990], [1777, 57.7, 870601776, 'India', 1990], [29550, 79.1, 122249285, 'Japan', 1990], [2076, 67.9, 20194354, 'North Korea', 1990], [12087, 72, 42972254, 'South Korea', 1990], [24021, 75.4, 3397534, 'New Zealand', 1990], [43296, 76.8, 4240375, 'Norway', 1990], [10088, 70.8, 38195258, 'Poland', 1990], [19349, 69.6, 147568552, 'Russia', 1990], [10670, 67.3, 53994605, 'Turkey', 1990], [26424, 75.7, 57110117, 'United Kingdom', 1990], [37062, 75.4, 252847810, 'United States', 1990], ], type: 'scatter', itemStyle: { opacity: 0.75, color: '#007373', }, symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; }, label: { show: true, formatter(param: any): any { return param.data[3]; }, position: 'top', }, }, { name: '2015', data: [ [44056, 81.8, 23968973, 'Australia', 2015], [43294, 81.7, 35939927, 'Canada', 2015], [13334, 76.9, 1376048943, 'China', 2015], [21291, 78.5, 11389562, 'Cuba', 2015], [38923, 80.8, 5503457, 'Finland', 2015], [37599, 81.9, 64395345, 'France', 2015], [44053, 81.1, 80688545, 'Germany', 2015], [42182, 82.8, 329425, 'Iceland', 2015], [5903, 66.8, 1311050527, 'India', 2015], [36162, 83.5, 126573481, 'Japan', 2015], [1390, 71.4, 25155317, 'North Korea', 2015], [34644, 80.7, 50293439, 'South Korea', 2015], [34186, 80.6, 4528526, 'New Zealand', 2015], [64304, 81.6, 5210967, 'Norway', 2015], [24787, 77.3, 38611794, 'Poland', 2015], [23038, 73.13, 143456918, 'Russia', 2015], [19360, 76.5, 78665830, 'Turkey', 2015], [38225, 81.4, 64715810, 'United Kingdom', 2015], [53354, 79.1, 321773631, 'United States', 2015], ], type: 'scatter', itemStyle: { opacity: 0.75, color: '#1B98C6', }, symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; }, label: { show: true, formatter(param: any): any { return param.data[3]; }, position: 'top', }, }, ], }; constructor(private _cdr: ChangeDetectorRef, public themeSelector: ChartThemeSelectorService)
async ngOnInit(): Promise<void> { this.selectedTheme = this.themeSelector.selected; this._cdr.markForCheck(); } selectChartTheme(theme: string): void { this.themeSelector.select(theme); } symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; } }
{}
identifier_body
scatter-demo-basic.component.ts
import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef } from '@angular/core'; import { getThemes } from '@covalent/echarts/base'; import { ChartThemeSelectorService } from '../../../../../../utilities/chart-theme'; @Component({ selector: 'scatter-demo-basic', styleUrls: ['./scatter-demo-basic.component.scss'], templateUrl: './scatter-demo-basic.component.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class ScatterDemoBasicComponent implements OnInit { themes: string[] = getThemes(); selectedTheme: string; config: any = { tooltip: { show: true, }, legend: { right: 10, data: ['1990', '2015'], }, xAxis: [{ show: true }], yAxis: [{ show: true }], series: [ { name: '1990', data: [ [28604, 77, 17096869, 'Australia', 1990], [31163, 77.4, 27662440, 'Canada', 1990], [1516, 68, 1154605773, 'China', 1990], [13670, 74.7, 10582082, 'Cuba', 1990], [28599, 75, 4986705, 'Finland', 1990], [29476, 77.1, 56943299, 'France', 1990], [31476, 75.4, 78958237, 'Germany', 1990], [28666, 78.1, 254830, 'Iceland', 1990], [1777, 57.7, 870601776, 'India', 1990], [29550, 79.1, 122249285, 'Japan', 1990], [2076, 67.9, 20194354, 'North Korea', 1990], [12087, 72, 42972254, 'South Korea', 1990], [24021, 75.4, 3397534, 'New Zealand', 1990], [43296, 76.8, 4240375, 'Norway', 1990], [10088, 70.8, 38195258, 'Poland', 1990], [19349, 69.6, 147568552, 'Russia', 1990], [10670, 67.3, 53994605, 'Turkey', 1990], [26424, 75.7, 57110117, 'United Kingdom', 1990], [37062, 75.4, 252847810, 'United States', 1990], ], type: 'scatter', itemStyle: { opacity: 0.75, color: '#007373', }, symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; }, label: { show: true, formatter(param: any): any { return param.data[3]; }, position: 'top', }, }, { name: '2015', data: [ [44056, 81.8, 23968973, 'Australia', 2015], [43294, 81.7, 35939927, 'Canada', 2015], [13334, 76.9, 1376048943, 'China', 2015], [21291, 78.5, 11389562, 'Cuba', 2015], [38923, 80.8, 5503457, 'Finland', 2015], [37599, 81.9, 64395345, 'France', 2015], [44053, 81.1, 80688545, 'Germany', 2015], [42182, 82.8, 329425, 'Iceland', 2015], [5903, 66.8, 1311050527, 'India', 2015], [36162, 83.5, 126573481, 'Japan', 2015], [1390, 71.4, 25155317, 'North Korea', 2015], [34644, 80.7, 50293439, 'South Korea', 2015], [34186, 80.6, 4528526, 'New Zealand', 2015], [64304, 81.6, 5210967, 'Norway', 2015],
[23038, 73.13, 143456918, 'Russia', 2015], [19360, 76.5, 78665830, 'Turkey', 2015], [38225, 81.4, 64715810, 'United Kingdom', 2015], [53354, 79.1, 321773631, 'United States', 2015], ], type: 'scatter', itemStyle: { opacity: 0.75, color: '#1B98C6', }, symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; }, label: { show: true, formatter(param: any): any { return param.data[3]; }, position: 'top', }, }, ], }; constructor(private _cdr: ChangeDetectorRef, public themeSelector: ChartThemeSelectorService) {} async ngOnInit(): Promise<void> { this.selectedTheme = this.themeSelector.selected; this._cdr.markForCheck(); } selectChartTheme(theme: string): void { this.themeSelector.select(theme); } symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; } }
[24787, 77.3, 38611794, 'Poland', 2015],
random_line_split
remote_try_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import mox import os import sys import shutil import time import constants sys.path.insert(0, constants.SOURCE_ROOT) from chromite.lib import cros_build_lib from chromite.lib import cros_test_lib from chromite.lib import git from chromite.buildbot import remote_try from chromite.buildbot import repository from chromite.scripts import cbuildbot class RemoteTryJobMock(remote_try.RemoteTryJob): pass # pylint: disable=W0212,R0904,E1101 class RemoteTryTests(cros_test_lib.MoxTempDirTestCase): PATCHES = ('5555', '6666') BOTS = ('x86-generic-paladin', 'arm-generic-paladin') def setUp(self): self.parser = cbuildbot._CreateParser() args = ['-r', '/tmp/test_build1', '-g', '5555', '-g', '6666', '--remote'] args.extend(self.BOTS) self.options, args = cbuildbot._ParseCommandLine(self.parser, args) self.checkout_dir = os.path.join(self.tempdir, 'test_checkout') self.int_mirror, self.ext_mirror = None, None def _RunCommandSingleOutput(self, cmd, cwd): result = cros_build_lib.RunCommandCaptureOutput(cmd, cwd=cwd) out_lines = result.output.split() self.assertEqual(len(out_lines), 1) return out_lines[0] def _GetNewestFile(self, dirname, basehash): newhash = git.GetGitRepoRevision(dirname) self.assertNotEqual(basehash, newhash) cmd = ['git', 'log', '--format=%H', '%s..' % basehash] # Make sure we have a single commit. self._RunCommandSingleOutput(cmd, cwd=dirname) cmd = ['git', 'diff', '--name-only', 'HEAD^'] # Make sure only one file per commit. return self._RunCommandSingleOutput(cmd, cwd=dirname) def _SubmitJob(self, checkout_dir, job, version=None): """Returns the path to the tryjob description.""" self.assertTrue(isinstance(job, RemoteTryJobMock)) basehash = git.GetGitRepoRevision(job.ssh_url) if version is not None: self._SetMirrorVersion(version) job.Submit(workdir=checkout_dir, dryrun=True) # Get the file that was just created. created_file = self._GetNewestFile(checkout_dir, basehash) return os.path.join(checkout_dir, created_file) def _SetupMirrors(self): mirror = os.path.join(self.tempdir, 'tryjobs_mirror') os.mkdir(mirror) url = '%s/%s' % (constants.GIT_HTTP_URL, 'chromiumos/tryjobs') repository.CloneGitRepo(mirror, url, bare=True) self.ext_mirror = mirror mirror = os.path.join(self.tempdir, 'tryjobs_int_mirror') os.mkdir(mirror) repository.CloneGitRepo(mirror, self.ext_mirror, reference=self.ext_mirror, bare=True) self.int_mirror = mirror RemoteTryJobMock.EXT_SSH_URL = self.ext_mirror RemoteTryJobMock.INT_SSH_URL = self.int_mirror self._SetMirrorVersion(remote_try.RemoteTryJob.TRYJOB_FORMAT_VERSION, True) def _SetMirrorVersion(self, version, only_if_missing=False): for path in (self.ext_mirror, self.int_mirror): vpath = os.path.join(path, remote_try.RemoteTryJob.TRYJOB_FORMAT_FILE) if os.path.exists(vpath) and only_if_missing:
# Get ourselves a working dir. tmp_repo = os.path.join(self.tempdir, 'tmp-repo') git.RunGit(self.tempdir, ['clone', path, tmp_repo]) vpath = os.path.join(tmp_repo, remote_try.RemoteTryJob.TRYJOB_FORMAT_FILE) with open(vpath, 'w') as f: f.write(str(version)) git.RunGit(tmp_repo, ['add', vpath]) git.RunGit(tmp_repo, ['commit', '-m', 'setting version to %s' % version]) git.RunGit(tmp_repo, ['push', path, 'master:master']) shutil.rmtree(tmp_repo) def _CreateJob(self, mirror=True): job_class = remote_try.RemoteTryJob if mirror: job_class = RemoteTryJobMock self._SetupMirrors() job = job_class(self.options, self.BOTS, []) return job def testJobTimestamp(self): """Verify jobs have unique names.""" def submit_helper(dirname): work_dir = os.path.join(self.tempdir, dirname) return os.path.basename(self._SubmitJob(work_dir, job)) self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(False) self.mox.ReplayAll() job = self._CreateJob() file1 = submit_helper('test1') # Tryjob file names are based on timestamp, so delay one second to avoid two # jobfiles having the same name. time.sleep(1) file2 = submit_helper('test2') self.assertNotEqual(file1, file2) def testSimpleTryJob(self, version=None): """Test that a tryjob spec file is created and pushed properly.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(True) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') repository.IsInternalRepoCheckout(mox.IgnoreArg()).AndReturn(False) self.mox.ReplayAll() try: os.environ["GIT_AUTHOR_EMAIL"] = "Elmer Fudd <efudd@google.com>" os.environ["GIT_COMMITTER_EMAIL"] = "Elmer Fudd <efudd@google.com>" job = self._CreateJob() finally: os.environ.pop("GIT_AUTHOR_EMAIL", None) os.environ.pop("GIT_COMMITTER_EMAIL", None) created_file = self._SubmitJob(self.checkout_dir, job, version=version) with open(created_file, 'rb') as job_desc_file: values = json.load(job_desc_file) self.assertTrue('efudd@google.com' in values['email'][0]) for patch in self.PATCHES: self.assertTrue(patch in values['extra_args'], msg="expected patch %s in args %s" % (patch, values['extra_args'])) self.assertTrue(set(self.BOTS).issubset(values['bot'])) remote_url = cros_build_lib.RunCommand( ['git', 'config', 'remote.origin.url'], redirect_stdout=True, cwd=self.checkout_dir).output.strip() self.assertEqual(remote_url, self.ext_mirror) def testClientVersionAwareness(self): self.assertRaises( remote_try.ChromiteUpgradeNeeded, self.testSimpleTryJob, version=remote_try.RemoteTryJob.TRYJOB_FORMAT_VERSION + 1) def testInternalTryJob(self): """Verify internal tryjobs are pushed properly.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(True) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') repository.IsInternalRepoCheckout(mox.IgnoreArg()).AndReturn(True) self.mox.ReplayAll() job = self._CreateJob() self._SubmitJob(self.checkout_dir, job) remote_url = cros_build_lib.RunCommand( ['git', 'config', 'remote.origin.url'], redirect_stdout=True, cwd=self.checkout_dir).output.strip() self.assertEqual(remote_url, self.int_mirror) def testBareTryJob(self): """Verify submitting a tryjob from just a chromite checkout works.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(False) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') self.mox.ReplayAll() job = self._CreateJob(mirror=False) self.assertEqual(job.ssh_url, remote_try.RemoteTryJob.EXT_SSH_URL) if __name__ == '__main__': cros_test_lib.main()
continue
conditional_block
remote_try_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import mox import os import sys import shutil import time import constants sys.path.insert(0, constants.SOURCE_ROOT) from chromite.lib import cros_build_lib from chromite.lib import cros_test_lib from chromite.lib import git from chromite.buildbot import remote_try from chromite.buildbot import repository from chromite.scripts import cbuildbot class RemoteTryJobMock(remote_try.RemoteTryJob): pass # pylint: disable=W0212,R0904,E1101 class RemoteTryTests(cros_test_lib.MoxTempDirTestCase): PATCHES = ('5555', '6666') BOTS = ('x86-generic-paladin', 'arm-generic-paladin') def setUp(self):
def _RunCommandSingleOutput(self, cmd, cwd): result = cros_build_lib.RunCommandCaptureOutput(cmd, cwd=cwd) out_lines = result.output.split() self.assertEqual(len(out_lines), 1) return out_lines[0] def _GetNewestFile(self, dirname, basehash): newhash = git.GetGitRepoRevision(dirname) self.assertNotEqual(basehash, newhash) cmd = ['git', 'log', '--format=%H', '%s..' % basehash] # Make sure we have a single commit. self._RunCommandSingleOutput(cmd, cwd=dirname) cmd = ['git', 'diff', '--name-only', 'HEAD^'] # Make sure only one file per commit. return self._RunCommandSingleOutput(cmd, cwd=dirname) def _SubmitJob(self, checkout_dir, job, version=None): """Returns the path to the tryjob description.""" self.assertTrue(isinstance(job, RemoteTryJobMock)) basehash = git.GetGitRepoRevision(job.ssh_url) if version is not None: self._SetMirrorVersion(version) job.Submit(workdir=checkout_dir, dryrun=True) # Get the file that was just created. created_file = self._GetNewestFile(checkout_dir, basehash) return os.path.join(checkout_dir, created_file) def _SetupMirrors(self): mirror = os.path.join(self.tempdir, 'tryjobs_mirror') os.mkdir(mirror) url = '%s/%s' % (constants.GIT_HTTP_URL, 'chromiumos/tryjobs') repository.CloneGitRepo(mirror, url, bare=True) self.ext_mirror = mirror mirror = os.path.join(self.tempdir, 'tryjobs_int_mirror') os.mkdir(mirror) repository.CloneGitRepo(mirror, self.ext_mirror, reference=self.ext_mirror, bare=True) self.int_mirror = mirror RemoteTryJobMock.EXT_SSH_URL = self.ext_mirror RemoteTryJobMock.INT_SSH_URL = self.int_mirror self._SetMirrorVersion(remote_try.RemoteTryJob.TRYJOB_FORMAT_VERSION, True) def _SetMirrorVersion(self, version, only_if_missing=False): for path in (self.ext_mirror, self.int_mirror): vpath = os.path.join(path, remote_try.RemoteTryJob.TRYJOB_FORMAT_FILE) if os.path.exists(vpath) and only_if_missing: continue # Get ourselves a working dir. tmp_repo = os.path.join(self.tempdir, 'tmp-repo') git.RunGit(self.tempdir, ['clone', path, tmp_repo]) vpath = os.path.join(tmp_repo, remote_try.RemoteTryJob.TRYJOB_FORMAT_FILE) with open(vpath, 'w') as f: f.write(str(version)) git.RunGit(tmp_repo, ['add', vpath]) git.RunGit(tmp_repo, ['commit', '-m', 'setting version to %s' % version]) git.RunGit(tmp_repo, ['push', path, 'master:master']) shutil.rmtree(tmp_repo) def _CreateJob(self, mirror=True): job_class = remote_try.RemoteTryJob if mirror: job_class = RemoteTryJobMock self._SetupMirrors() job = job_class(self.options, self.BOTS, []) return job def testJobTimestamp(self): """Verify jobs have unique names.""" def submit_helper(dirname): work_dir = os.path.join(self.tempdir, dirname) return os.path.basename(self._SubmitJob(work_dir, job)) self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(False) self.mox.ReplayAll() job = self._CreateJob() file1 = submit_helper('test1') # Tryjob file names are based on timestamp, so delay one second to avoid two # jobfiles having the same name. time.sleep(1) file2 = submit_helper('test2') self.assertNotEqual(file1, file2) def testSimpleTryJob(self, version=None): """Test that a tryjob spec file is created and pushed properly.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(True) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') repository.IsInternalRepoCheckout(mox.IgnoreArg()).AndReturn(False) self.mox.ReplayAll() try: os.environ["GIT_AUTHOR_EMAIL"] = "Elmer Fudd <efudd@google.com>" os.environ["GIT_COMMITTER_EMAIL"] = "Elmer Fudd <efudd@google.com>" job = self._CreateJob() finally: os.environ.pop("GIT_AUTHOR_EMAIL", None) os.environ.pop("GIT_COMMITTER_EMAIL", None) created_file = self._SubmitJob(self.checkout_dir, job, version=version) with open(created_file, 'rb') as job_desc_file: values = json.load(job_desc_file) self.assertTrue('efudd@google.com' in values['email'][0]) for patch in self.PATCHES: self.assertTrue(patch in values['extra_args'], msg="expected patch %s in args %s" % (patch, values['extra_args'])) self.assertTrue(set(self.BOTS).issubset(values['bot'])) remote_url = cros_build_lib.RunCommand( ['git', 'config', 'remote.origin.url'], redirect_stdout=True, cwd=self.checkout_dir).output.strip() self.assertEqual(remote_url, self.ext_mirror) def testClientVersionAwareness(self): self.assertRaises( remote_try.ChromiteUpgradeNeeded, self.testSimpleTryJob, version=remote_try.RemoteTryJob.TRYJOB_FORMAT_VERSION + 1) def testInternalTryJob(self): """Verify internal tryjobs are pushed properly.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(True) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') repository.IsInternalRepoCheckout(mox.IgnoreArg()).AndReturn(True) self.mox.ReplayAll() job = self._CreateJob() self._SubmitJob(self.checkout_dir, job) remote_url = cros_build_lib.RunCommand( ['git', 'config', 'remote.origin.url'], redirect_stdout=True, cwd=self.checkout_dir).output.strip() self.assertEqual(remote_url, self.int_mirror) def testBareTryJob(self): """Verify submitting a tryjob from just a chromite checkout works.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(False) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') self.mox.ReplayAll() job = self._CreateJob(mirror=False) self.assertEqual(job.ssh_url, remote_try.RemoteTryJob.EXT_SSH_URL) if __name__ == '__main__': cros_test_lib.main()
self.parser = cbuildbot._CreateParser() args = ['-r', '/tmp/test_build1', '-g', '5555', '-g', '6666', '--remote'] args.extend(self.BOTS) self.options, args = cbuildbot._ParseCommandLine(self.parser, args) self.checkout_dir = os.path.join(self.tempdir, 'test_checkout') self.int_mirror, self.ext_mirror = None, None
identifier_body
remote_try_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import mox import os import sys import shutil import time import constants sys.path.insert(0, constants.SOURCE_ROOT) from chromite.lib import cros_build_lib from chromite.lib import cros_test_lib from chromite.lib import git from chromite.buildbot import remote_try from chromite.buildbot import repository from chromite.scripts import cbuildbot class RemoteTryJobMock(remote_try.RemoteTryJob): pass # pylint: disable=W0212,R0904,E1101 class RemoteTryTests(cros_test_lib.MoxTempDirTestCase): PATCHES = ('5555', '6666') BOTS = ('x86-generic-paladin', 'arm-generic-paladin') def setUp(self): self.parser = cbuildbot._CreateParser() args = ['-r', '/tmp/test_build1', '-g', '5555', '-g', '6666', '--remote'] args.extend(self.BOTS) self.options, args = cbuildbot._ParseCommandLine(self.parser, args) self.checkout_dir = os.path.join(self.tempdir, 'test_checkout') self.int_mirror, self.ext_mirror = None, None def _RunCommandSingleOutput(self, cmd, cwd): result = cros_build_lib.RunCommandCaptureOutput(cmd, cwd=cwd) out_lines = result.output.split() self.assertEqual(len(out_lines), 1) return out_lines[0] def _GetNewestFile(self, dirname, basehash): newhash = git.GetGitRepoRevision(dirname) self.assertNotEqual(basehash, newhash) cmd = ['git', 'log', '--format=%H', '%s..' % basehash] # Make sure we have a single commit. self._RunCommandSingleOutput(cmd, cwd=dirname) cmd = ['git', 'diff', '--name-only', 'HEAD^'] # Make sure only one file per commit. return self._RunCommandSingleOutput(cmd, cwd=dirname) def _SubmitJob(self, checkout_dir, job, version=None): """Returns the path to the tryjob description.""" self.assertTrue(isinstance(job, RemoteTryJobMock)) basehash = git.GetGitRepoRevision(job.ssh_url) if version is not None: self._SetMirrorVersion(version) job.Submit(workdir=checkout_dir, dryrun=True) # Get the file that was just created. created_file = self._GetNewestFile(checkout_dir, basehash) return os.path.join(checkout_dir, created_file) def _SetupMirrors(self): mirror = os.path.join(self.tempdir, 'tryjobs_mirror') os.mkdir(mirror) url = '%s/%s' % (constants.GIT_HTTP_URL, 'chromiumos/tryjobs') repository.CloneGitRepo(mirror, url, bare=True) self.ext_mirror = mirror mirror = os.path.join(self.tempdir, 'tryjobs_int_mirror') os.mkdir(mirror) repository.CloneGitRepo(mirror, self.ext_mirror, reference=self.ext_mirror, bare=True) self.int_mirror = mirror RemoteTryJobMock.EXT_SSH_URL = self.ext_mirror RemoteTryJobMock.INT_SSH_URL = self.int_mirror self._SetMirrorVersion(remote_try.RemoteTryJob.TRYJOB_FORMAT_VERSION, True) def _SetMirrorVersion(self, version, only_if_missing=False): for path in (self.ext_mirror, self.int_mirror): vpath = os.path.join(path, remote_try.RemoteTryJob.TRYJOB_FORMAT_FILE) if os.path.exists(vpath) and only_if_missing: continue # Get ourselves a working dir. tmp_repo = os.path.join(self.tempdir, 'tmp-repo') git.RunGit(self.tempdir, ['clone', path, tmp_repo]) vpath = os.path.join(tmp_repo, remote_try.RemoteTryJob.TRYJOB_FORMAT_FILE) with open(vpath, 'w') as f: f.write(str(version)) git.RunGit(tmp_repo, ['add', vpath]) git.RunGit(tmp_repo, ['commit', '-m', 'setting version to %s' % version]) git.RunGit(tmp_repo, ['push', path, 'master:master']) shutil.rmtree(tmp_repo) def _CreateJob(self, mirror=True): job_class = remote_try.RemoteTryJob
job = job_class(self.options, self.BOTS, []) return job def testJobTimestamp(self): """Verify jobs have unique names.""" def submit_helper(dirname): work_dir = os.path.join(self.tempdir, dirname) return os.path.basename(self._SubmitJob(work_dir, job)) self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(False) self.mox.ReplayAll() job = self._CreateJob() file1 = submit_helper('test1') # Tryjob file names are based on timestamp, so delay one second to avoid two # jobfiles having the same name. time.sleep(1) file2 = submit_helper('test2') self.assertNotEqual(file1, file2) def testSimpleTryJob(self, version=None): """Test that a tryjob spec file is created and pushed properly.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(True) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') repository.IsInternalRepoCheckout(mox.IgnoreArg()).AndReturn(False) self.mox.ReplayAll() try: os.environ["GIT_AUTHOR_EMAIL"] = "Elmer Fudd <efudd@google.com>" os.environ["GIT_COMMITTER_EMAIL"] = "Elmer Fudd <efudd@google.com>" job = self._CreateJob() finally: os.environ.pop("GIT_AUTHOR_EMAIL", None) os.environ.pop("GIT_COMMITTER_EMAIL", None) created_file = self._SubmitJob(self.checkout_dir, job, version=version) with open(created_file, 'rb') as job_desc_file: values = json.load(job_desc_file) self.assertTrue('efudd@google.com' in values['email'][0]) for patch in self.PATCHES: self.assertTrue(patch in values['extra_args'], msg="expected patch %s in args %s" % (patch, values['extra_args'])) self.assertTrue(set(self.BOTS).issubset(values['bot'])) remote_url = cros_build_lib.RunCommand( ['git', 'config', 'remote.origin.url'], redirect_stdout=True, cwd=self.checkout_dir).output.strip() self.assertEqual(remote_url, self.ext_mirror) def testClientVersionAwareness(self): self.assertRaises( remote_try.ChromiteUpgradeNeeded, self.testSimpleTryJob, version=remote_try.RemoteTryJob.TRYJOB_FORMAT_VERSION + 1) def testInternalTryJob(self): """Verify internal tryjobs are pushed properly.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(True) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') repository.IsInternalRepoCheckout(mox.IgnoreArg()).AndReturn(True) self.mox.ReplayAll() job = self._CreateJob() self._SubmitJob(self.checkout_dir, job) remote_url = cros_build_lib.RunCommand( ['git', 'config', 'remote.origin.url'], redirect_stdout=True, cwd=self.checkout_dir).output.strip() self.assertEqual(remote_url, self.int_mirror) def testBareTryJob(self): """Verify submitting a tryjob from just a chromite checkout works.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(False) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') self.mox.ReplayAll() job = self._CreateJob(mirror=False) self.assertEqual(job.ssh_url, remote_try.RemoteTryJob.EXT_SSH_URL) if __name__ == '__main__': cros_test_lib.main()
if mirror: job_class = RemoteTryJobMock self._SetupMirrors()
random_line_split
remote_try_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import mox import os import sys import shutil import time import constants sys.path.insert(0, constants.SOURCE_ROOT) from chromite.lib import cros_build_lib from chromite.lib import cros_test_lib from chromite.lib import git from chromite.buildbot import remote_try from chromite.buildbot import repository from chromite.scripts import cbuildbot class RemoteTryJobMock(remote_try.RemoteTryJob): pass # pylint: disable=W0212,R0904,E1101 class RemoteTryTests(cros_test_lib.MoxTempDirTestCase): PATCHES = ('5555', '6666') BOTS = ('x86-generic-paladin', 'arm-generic-paladin') def setUp(self): self.parser = cbuildbot._CreateParser() args = ['-r', '/tmp/test_build1', '-g', '5555', '-g', '6666', '--remote'] args.extend(self.BOTS) self.options, args = cbuildbot._ParseCommandLine(self.parser, args) self.checkout_dir = os.path.join(self.tempdir, 'test_checkout') self.int_mirror, self.ext_mirror = None, None def _RunCommandSingleOutput(self, cmd, cwd): result = cros_build_lib.RunCommandCaptureOutput(cmd, cwd=cwd) out_lines = result.output.split() self.assertEqual(len(out_lines), 1) return out_lines[0] def _GetNewestFile(self, dirname, basehash): newhash = git.GetGitRepoRevision(dirname) self.assertNotEqual(basehash, newhash) cmd = ['git', 'log', '--format=%H', '%s..' % basehash] # Make sure we have a single commit. self._RunCommandSingleOutput(cmd, cwd=dirname) cmd = ['git', 'diff', '--name-only', 'HEAD^'] # Make sure only one file per commit. return self._RunCommandSingleOutput(cmd, cwd=dirname) def _SubmitJob(self, checkout_dir, job, version=None): """Returns the path to the tryjob description.""" self.assertTrue(isinstance(job, RemoteTryJobMock)) basehash = git.GetGitRepoRevision(job.ssh_url) if version is not None: self._SetMirrorVersion(version) job.Submit(workdir=checkout_dir, dryrun=True) # Get the file that was just created. created_file = self._GetNewestFile(checkout_dir, basehash) return os.path.join(checkout_dir, created_file) def _SetupMirrors(self): mirror = os.path.join(self.tempdir, 'tryjobs_mirror') os.mkdir(mirror) url = '%s/%s' % (constants.GIT_HTTP_URL, 'chromiumos/tryjobs') repository.CloneGitRepo(mirror, url, bare=True) self.ext_mirror = mirror mirror = os.path.join(self.tempdir, 'tryjobs_int_mirror') os.mkdir(mirror) repository.CloneGitRepo(mirror, self.ext_mirror, reference=self.ext_mirror, bare=True) self.int_mirror = mirror RemoteTryJobMock.EXT_SSH_URL = self.ext_mirror RemoteTryJobMock.INT_SSH_URL = self.int_mirror self._SetMirrorVersion(remote_try.RemoteTryJob.TRYJOB_FORMAT_VERSION, True) def _SetMirrorVersion(self, version, only_if_missing=False): for path in (self.ext_mirror, self.int_mirror): vpath = os.path.join(path, remote_try.RemoteTryJob.TRYJOB_FORMAT_FILE) if os.path.exists(vpath) and only_if_missing: continue # Get ourselves a working dir. tmp_repo = os.path.join(self.tempdir, 'tmp-repo') git.RunGit(self.tempdir, ['clone', path, tmp_repo]) vpath = os.path.join(tmp_repo, remote_try.RemoteTryJob.TRYJOB_FORMAT_FILE) with open(vpath, 'w') as f: f.write(str(version)) git.RunGit(tmp_repo, ['add', vpath]) git.RunGit(tmp_repo, ['commit', '-m', 'setting version to %s' % version]) git.RunGit(tmp_repo, ['push', path, 'master:master']) shutil.rmtree(tmp_repo) def _CreateJob(self, mirror=True): job_class = remote_try.RemoteTryJob if mirror: job_class = RemoteTryJobMock self._SetupMirrors() job = job_class(self.options, self.BOTS, []) return job def testJobTimestamp(self): """Verify jobs have unique names.""" def submit_helper(dirname): work_dir = os.path.join(self.tempdir, dirname) return os.path.basename(self._SubmitJob(work_dir, job)) self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(False) self.mox.ReplayAll() job = self._CreateJob() file1 = submit_helper('test1') # Tryjob file names are based on timestamp, so delay one second to avoid two # jobfiles having the same name. time.sleep(1) file2 = submit_helper('test2') self.assertNotEqual(file1, file2) def testSimpleTryJob(self, version=None): """Test that a tryjob spec file is created and pushed properly.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(True) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') repository.IsInternalRepoCheckout(mox.IgnoreArg()).AndReturn(False) self.mox.ReplayAll() try: os.environ["GIT_AUTHOR_EMAIL"] = "Elmer Fudd <efudd@google.com>" os.environ["GIT_COMMITTER_EMAIL"] = "Elmer Fudd <efudd@google.com>" job = self._CreateJob() finally: os.environ.pop("GIT_AUTHOR_EMAIL", None) os.environ.pop("GIT_COMMITTER_EMAIL", None) created_file = self._SubmitJob(self.checkout_dir, job, version=version) with open(created_file, 'rb') as job_desc_file: values = json.load(job_desc_file) self.assertTrue('efudd@google.com' in values['email'][0]) for patch in self.PATCHES: self.assertTrue(patch in values['extra_args'], msg="expected patch %s in args %s" % (patch, values['extra_args'])) self.assertTrue(set(self.BOTS).issubset(values['bot'])) remote_url = cros_build_lib.RunCommand( ['git', 'config', 'remote.origin.url'], redirect_stdout=True, cwd=self.checkout_dir).output.strip() self.assertEqual(remote_url, self.ext_mirror) def
(self): self.assertRaises( remote_try.ChromiteUpgradeNeeded, self.testSimpleTryJob, version=remote_try.RemoteTryJob.TRYJOB_FORMAT_VERSION + 1) def testInternalTryJob(self): """Verify internal tryjobs are pushed properly.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(True) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') repository.IsInternalRepoCheckout(mox.IgnoreArg()).AndReturn(True) self.mox.ReplayAll() job = self._CreateJob() self._SubmitJob(self.checkout_dir, job) remote_url = cros_build_lib.RunCommand( ['git', 'config', 'remote.origin.url'], redirect_stdout=True, cwd=self.checkout_dir).output.strip() self.assertEqual(remote_url, self.int_mirror) def testBareTryJob(self): """Verify submitting a tryjob from just a chromite checkout works.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') repository.IsARepoRoot(mox.IgnoreArg()).AndReturn(False) self.mox.StubOutWithMock(repository, 'IsInternalRepoCheckout') self.mox.ReplayAll() job = self._CreateJob(mirror=False) self.assertEqual(job.ssh_url, remote_try.RemoteTryJob.EXT_SSH_URL) if __name__ == '__main__': cros_test_lib.main()
testClientVersionAwareness
identifier_name
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1); pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin { WhoAmIPlugin } pub fn get_plugin_name() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType>
impl RustBotPlugin for WhoAmIPlugin { fn configure(&mut self, conf: &mut IrcBotConfigurator) { conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap()); conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap()); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) { let privmsg; match msg.as_tymsg::<&server::Privmsg>() { Ok(p) => privmsg = p, Err(_) => return, } match parse_command(m) { Some(WhoAmICommandType::WhoAmI) => { m.reply(&format!("{}: you are {:?}", privmsg.source_nick(), m.source)); }, Some(WhoAmICommandType::WhereAmI) => { m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target)); }, None => () } } }
{ match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI), _ => None } }
identifier_body
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1); pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin { WhoAmIPlugin } pub fn
() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> { match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI), _ => None } } impl RustBotPlugin for WhoAmIPlugin { fn configure(&mut self, conf: &mut IrcBotConfigurator) { conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap()); conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap()); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) { let privmsg; match msg.as_tymsg::<&server::Privmsg>() { Ok(p) => privmsg = p, Err(_) => return, } match parse_command(m) { Some(WhoAmICommandType::WhoAmI) => { m.reply(&format!("{}: you are {:?}", privmsg.source_nick(), m.source)); }, Some(WhoAmICommandType::WhereAmI) => { m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target)); }, None => () } } }
get_plugin_name
identifier_name
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1);
WhoAmIPlugin } pub fn get_plugin_name() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> { match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI), _ => None } } impl RustBotPlugin for WhoAmIPlugin { fn configure(&mut self, conf: &mut IrcBotConfigurator) { conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap()); conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap()); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) { let privmsg; match msg.as_tymsg::<&server::Privmsg>() { Ok(p) => privmsg = p, Err(_) => return, } match parse_command(m) { Some(WhoAmICommandType::WhoAmI) => { m.reply(&format!("{}: you are {:?}", privmsg.source_nick(), m.source)); }, Some(WhoAmICommandType::WhereAmI) => { m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target)); }, None => () } } }
pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin {
random_line_split
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1); pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin { WhoAmIPlugin } pub fn get_plugin_name() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> { match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI), _ => None } } impl RustBotPlugin for WhoAmIPlugin { fn configure(&mut self, conf: &mut IrcBotConfigurator) { conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap()); conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap()); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, msg: &IrcMsg) { let privmsg; match msg.as_tymsg::<&server::Privmsg>() { Ok(p) => privmsg = p, Err(_) => return, } match parse_command(m) { Some(WhoAmICommandType::WhoAmI) => { m.reply(&format!("{}: you are {:?}", privmsg.source_nick(), m.source)); }, Some(WhoAmICommandType::WhereAmI) =>
, None => () } } }
{ m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target)); }
conditional_block
generatorBase.ts
import { TemplateEngine } from './templateEngine'; export abstract class OpGeneratorBase { /** * Name of the object used to inject dependencies. * In the generated functions, the dependencies are accessed via * `__dep__.Dependency`. */ public readonly DEP_OBJ_NAME = '__dep__'; protected _engine: TemplateEngine; protected constructor() { this._engine = new TemplateEngine(); } /** * Checks the symbols used in the given code. Throws when encounters any * symbol that is not allowed. Returns a list of used symbols. * @param code Block of code to be checked. * @param allowed A list of allowed symbols. Case sensitive. */ protected _checkUsedSymbols(code: string, allowed: string[]): string[] { let reSymbol = /\$\w+/g; let m: RegExpExecArray | null; let used: {[key: string]: boolean} = {}; while (m = reSymbol.exec(code)) { if (allowed.indexOf(m[0]) < 0) { throw new Error(`Symbol ${m[0]} is not permitted in the following code:\n${code}`); } used[m[0]] = true; } let result: string[] = []; for (let prop in used) { if (used.hasOwnProperty(prop)) { result.push(prop); } } return result; } /** * Converts inline functions to string. * @param fs Functions to be converted. */ protected
(fs: {[key: string]: Function}): string { let result = ''; for (let key in fs) { if (fs.hasOwnProperty(key)) { let fStr = fs[key].toString(); if (fStr.indexOf('[native code]') > 0) { throw new Error('Cannot inline native functions.'); } // replace function name let idxFirstP = fStr.indexOf('('); if (idxFirstP < 0) { throw new Error('Cannot find the first pair of parenthesis.'); } // note that the specified function name is NOT checked fStr = 'function ' + key + fStr.substr(idxFirstP); result += fStr + '\n'; } } return result; } /** * Generate the code block to import dependencies. * @param depNames Dependency names (accessible from depObjName). * @example * _generateDependencyBlock('__dep__', ['Core', 'Utils']); * // var Core = __dep__.Core; * // var Utils = __dep__.Utils; */ protected _generateDependencyBlock(depNames: string[]): string { return depNames.map(x => `var ${x} = ${this.DEP_OBJ_NAME}.${x};`).join('\n'); } }
_flattenInlineFunctions
identifier_name
generatorBase.ts
import { TemplateEngine } from './templateEngine'; export abstract class OpGeneratorBase { /** * Name of the object used to inject dependencies. * In the generated functions, the dependencies are accessed via * `__dep__.Dependency`. */ public readonly DEP_OBJ_NAME = '__dep__'; protected _engine: TemplateEngine; protected constructor() { this._engine = new TemplateEngine(); } /** * Checks the symbols used in the given code. Throws when encounters any * symbol that is not allowed. Returns a list of used symbols. * @param code Block of code to be checked. * @param allowed A list of allowed symbols. Case sensitive. */ protected _checkUsedSymbols(code: string, allowed: string[]): string[] { let reSymbol = /\$\w+/g; let m: RegExpExecArray | null; let used: {[key: string]: boolean} = {}; while (m = reSymbol.exec(code)) { if (allowed.indexOf(m[0]) < 0) { throw new Error(`Symbol ${m[0]} is not permitted in the following code:\n${code}`); } used[m[0]] = true; } let result: string[] = []; for (let prop in used) { if (used.hasOwnProperty(prop)) { result.push(prop); } } return result; } /** * Converts inline functions to string. * @param fs Functions to be converted. */ protected _flattenInlineFunctions(fs: {[key: string]: Function}): string { let result = ''; for (let key in fs) { if (fs.hasOwnProperty(key)) { let fStr = fs[key].toString(); if (fStr.indexOf('[native code]') > 0)
// replace function name let idxFirstP = fStr.indexOf('('); if (idxFirstP < 0) { throw new Error('Cannot find the first pair of parenthesis.'); } // note that the specified function name is NOT checked fStr = 'function ' + key + fStr.substr(idxFirstP); result += fStr + '\n'; } } return result; } /** * Generate the code block to import dependencies. * @param depNames Dependency names (accessible from depObjName). * @example * _generateDependencyBlock('__dep__', ['Core', 'Utils']); * // var Core = __dep__.Core; * // var Utils = __dep__.Utils; */ protected _generateDependencyBlock(depNames: string[]): string { return depNames.map(x => `var ${x} = ${this.DEP_OBJ_NAME}.${x};`).join('\n'); } }
{ throw new Error('Cannot inline native functions.'); }
conditional_block
generatorBase.ts
import { TemplateEngine } from './templateEngine'; export abstract class OpGeneratorBase { /** * Name of the object used to inject dependencies. * In the generated functions, the dependencies are accessed via * `__dep__.Dependency`. */ public readonly DEP_OBJ_NAME = '__dep__'; protected _engine: TemplateEngine; protected constructor()
/** * Checks the symbols used in the given code. Throws when encounters any * symbol that is not allowed. Returns a list of used symbols. * @param code Block of code to be checked. * @param allowed A list of allowed symbols. Case sensitive. */ protected _checkUsedSymbols(code: string, allowed: string[]): string[] { let reSymbol = /\$\w+/g; let m: RegExpExecArray | null; let used: {[key: string]: boolean} = {}; while (m = reSymbol.exec(code)) { if (allowed.indexOf(m[0]) < 0) { throw new Error(`Symbol ${m[0]} is not permitted in the following code:\n${code}`); } used[m[0]] = true; } let result: string[] = []; for (let prop in used) { if (used.hasOwnProperty(prop)) { result.push(prop); } } return result; } /** * Converts inline functions to string. * @param fs Functions to be converted. */ protected _flattenInlineFunctions(fs: {[key: string]: Function}): string { let result = ''; for (let key in fs) { if (fs.hasOwnProperty(key)) { let fStr = fs[key].toString(); if (fStr.indexOf('[native code]') > 0) { throw new Error('Cannot inline native functions.'); } // replace function name let idxFirstP = fStr.indexOf('('); if (idxFirstP < 0) { throw new Error('Cannot find the first pair of parenthesis.'); } // note that the specified function name is NOT checked fStr = 'function ' + key + fStr.substr(idxFirstP); result += fStr + '\n'; } } return result; } /** * Generate the code block to import dependencies. * @param depNames Dependency names (accessible from depObjName). * @example * _generateDependencyBlock('__dep__', ['Core', 'Utils']); * // var Core = __dep__.Core; * // var Utils = __dep__.Utils; */ protected _generateDependencyBlock(depNames: string[]): string { return depNames.map(x => `var ${x} = ${this.DEP_OBJ_NAME}.${x};`).join('\n'); } }
{ this._engine = new TemplateEngine(); }
identifier_body
generatorBase.ts
import { TemplateEngine } from './templateEngine'; export abstract class OpGeneratorBase { /** * Name of the object used to inject dependencies. * In the generated functions, the dependencies are accessed via * `__dep__.Dependency`. */ public readonly DEP_OBJ_NAME = '__dep__'; protected _engine: TemplateEngine; protected constructor() { this._engine = new TemplateEngine(); } /** * Checks the symbols used in the given code. Throws when encounters any * symbol that is not allowed. Returns a list of used symbols. * @param code Block of code to be checked. * @param allowed A list of allowed symbols. Case sensitive. */ protected _checkUsedSymbols(code: string, allowed: string[]): string[] { let reSymbol = /\$\w+/g; let m: RegExpExecArray | null; let used: {[key: string]: boolean} = {}; while (m = reSymbol.exec(code)) { if (allowed.indexOf(m[0]) < 0) { throw new Error(`Symbol ${m[0]} is not permitted in the following code:\n${code}`); } used[m[0]] = true; } let result: string[] = []; for (let prop in used) { if (used.hasOwnProperty(prop)) {
} } return result; } /** * Converts inline functions to string. * @param fs Functions to be converted. */ protected _flattenInlineFunctions(fs: {[key: string]: Function}): string { let result = ''; for (let key in fs) { if (fs.hasOwnProperty(key)) { let fStr = fs[key].toString(); if (fStr.indexOf('[native code]') > 0) { throw new Error('Cannot inline native functions.'); } // replace function name let idxFirstP = fStr.indexOf('('); if (idxFirstP < 0) { throw new Error('Cannot find the first pair of parenthesis.'); } // note that the specified function name is NOT checked fStr = 'function ' + key + fStr.substr(idxFirstP); result += fStr + '\n'; } } return result; } /** * Generate the code block to import dependencies. * @param depNames Dependency names (accessible from depObjName). * @example * _generateDependencyBlock('__dep__', ['Core', 'Utils']); * // var Core = __dep__.Core; * // var Utils = __dep__.Utils; */ protected _generateDependencyBlock(depNames: string[]): string { return depNames.map(x => `var ${x} = ${this.DEP_OBJ_NAME}.${x};`).join('\n'); } }
result.push(prop);
random_line_split
manipulation.js
define([ "./core", "./var/strundefined", "./var/concat", "./var/push", "./var/deletedIds", "./core/access", "./manipulation/var/rcheckableType", "./manipulation/support", "./core/init", "./data/accepts", "./traversing", "./selector", "./event" ], function( jQuery, strundefined, concat, push, deletedIds, access, rcheckableType, support ) { function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function
( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); return jQuery; });
fixDefaultChecked
identifier_name
manipulation.js
define([ "./core", "./var/strundefined", "./var/concat", "./var/push", "./var/deletedIds", "./core/access", "./manipulation/var/rcheckableType", "./manipulation/support", "./core/init", "./data/accepts", "./traversing", "./selector", "./event" ], function( jQuery, strundefined, concat, push, deletedIds, access, rcheckableType, support ) { function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) )
else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); return jQuery; });
{ nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes }
conditional_block
manipulation.js
define([ "./core", "./var/strundefined", "./var/concat", "./var/push", "./var/deletedIds", "./core/access", "./manipulation/var/rcheckableType", "./manipulation/support", "./core/init", "./data/accepts", "./traversing", "./selector", "./event" ], function( jQuery, strundefined, concat, push, deletedIds, access, rcheckableType, support ) { function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem )
function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); return jQuery; });
{ elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; }
identifier_body
manipulation.js
define([ "./core", "./var/strundefined", "./var/concat", "./var/push", "./var/deletedIds", "./core/access", "./manipulation/var/rcheckableType", "./manipulation/support", "./core/init", "./data/accepts", "./traversing", "./selector", "./event" ], function( jQuery, strundefined, concat, push, deletedIds, access, rcheckableType, support ) { function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest );
} else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); return jQuery; });
// IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132.
random_line_split
typography.py
# -*- encoding: utf-8 -*- # # License: New BSD Style # # [typography.py][1] is a set of filters enhancing written text output. As the # name says, it adds specific typography things documented in the definitions # itself and [smartypants][2]. # # The typography.py filter comes with two options: ``mode`` and ``default``. # ``TYPOGRAPHY_MODE`` sets the `smartypants_attributes` as documented in [2]. # ``default`` (hard-coded) is a list of filters that will be always applied # if *typopgraphy* is invoked + everything you specify in the additional arguments. # # typopgraphy.py offers a custom mode, "a", that don't educate dashes when written # without space like *--bare* or *foo--* using mode "2". #
# [2]: http://web.chad.org/projects/smartypants.py/ import re import smartypants from acrylamid.filters import Filter class Typography(Filter): match = [re.compile('^(T|t)ypo(graphy)?$'), 'smartypants'] version = 2 priority = 25.0 def init(self, conf, env): self.mode = conf.get("typography_mode", "2") # -- en-dash, --- em-dash self.default = ['amp', 'widont', 'smartypants', 'caps'] if self.mode == "a": smartypants.educateDashes = new_dashes smartypants.educateDashesOldSchool = new_dashes self.mode = "2" self.ignore = env.options.ignore self.filters = {'amp': amp, 'widont': widont, 'caps': caps, 'initial_quotes': initial_quotes, 'number_suffix': number_suffix, 'typo': typogrify, 'typogrify': typogrify, 'all': typogrify, 'smartypants': smartypants.smartyPants} def transform(self, content, entry, *args): if any(filter(lambda k: k in args, ['all', 'typo', 'typogrify'])): return typogrify(content) for x in ['amp', 'widont', 'smartypants', 'caps', 'initial_quotes', 'number_suffix']: if x in self.default + list(args): if x == 'smartypants': content = self.filters[x](content, self.mode) else: content = self.filters[x](content) return content def new_dashes(str): # patching something-- to return something-- not something&#8212. str = re.sub(r"""(\s)--""", r"""\1&#8211;""", str) # en (yes, backwards) str = re.sub(r"""(\s)---""", r"""\1&#8212;""", str) # em (yes, backwards) return str def amp(text, autoescape=None): """Wraps apersands in HTML with ``<span class="amp">`` so they can be styled with CSS. Apersands are also normalized to ``&amp;``. Requires ampersands to have whitespace or an ``&nbsp;`` on both sides. >>> amp('One & two') u'One <span class="amp">&amp;</span> two' >>> amp('One &amp; two') u'One <span class="amp">&amp;</span> two' >>> amp('One &#38; two') u'One <span class="amp">&amp;</span> two' >>> amp('One&nbsp;&amp;&nbsp;two') u'One&nbsp;<span class="amp">&amp;</span>&nbsp;two' It won't mess up & that are already wrapped, in entities or URLs >>> amp('One <span class="amp">&amp;</span> two') u'One <span class="amp">&amp;</span> two' >>> amp('&ldquo;this&rdquo; & <a href="/?that&amp;test">that</a>') u'&ldquo;this&rdquo; <span class="amp">&amp;</span> <a href="/?that&amp;test">that</a>' It should ignore standalone amps that are in attributes >>> amp('<link href="xyz.html" title="One & Two">xyz</link>') u'<link href="xyz.html" title="One & Two">xyz</link>' """ # tag_pattern from http://haacked.com/archive/2004/10/25/usingregularexpressionstomatchhtml.aspx # it kinda sucks but it fixes the standalone amps in attributes bug tag_pattern = '</?\w+((\s+\w+(\s*=\s*(?:".*?"|\'.*?\'|[^\'">\s]+))?)+\s*|\s*)/?>' amp_finder = re.compile(r"(\s|&nbsp;)(&|&amp;|&\#38;)(\s|&nbsp;)") intra_tag_finder = re.compile(r'(?P<prefix>(%s)?)(?P<text>([^<]*))(?P<suffix>(%s)?)' % (tag_pattern, tag_pattern)) def _amp_process(groups): prefix = groups.group('prefix') or '' text = amp_finder.sub(r"""\1<span class="amp">&amp;</span>\3""", groups.group('text')) suffix = groups.group('suffix') or '' return prefix + text + suffix return intra_tag_finder.sub(_amp_process, text) def caps(text): """Wraps multiple capital letters in ``<span class="caps">`` so they can be styled with CSS. >>> caps("A message from KU") u'A message from <span class="caps">KU</span>' Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't. >>> caps("<PRE>CAPS</pre> more CAPS") u'<PRE>CAPS</pre> more <span class="caps">CAPS</span>' >>> caps("A message from 2KU2 with digits") u'A message from <span class="caps">2KU2</span> with digits' >>> caps("Dotted caps followed by spaces should never include them in the wrap D.O.T. like so.") u'Dotted caps followed by spaces should never include them in the wrap <span class="caps">D.O.T.</span> like so.' All caps with with apostrophes in them shouldn't break. Only handles dump apostrophes though. >>> caps("JIMMY'S") u'<span class="caps">JIMMY\\'S</span>' >>> caps("<i>D.O.T.</i>HE34T<b>RFID</b>") u'<i><span class="caps">D.O.T.</span></i><span class="caps">HE34T</span><b><span class="caps">RFID</span></b>' """ tokens = smartypants._tokenize(text) result = [] in_skipped_tag = False cap_finder = re.compile(r"""( (\b[A-Z\d]* # Group 2: Any amount of caps and digits [A-Z]\d*[A-Z] # A cap string must at least include two caps (but they can have digits between them) [A-Z\d']*\b) # Any amount of caps and digits or dumb apostsrophes | (\b[A-Z]+\.\s? # OR: Group 3: Some caps, followed by a '.' and an optional space (?:[A-Z]+\.\s?)+) # Followed by the same thing at least once more (?:\s|\b|$)) """, re.VERBOSE) def _cap_wrapper(matchobj): """This is necessary to keep dotted cap strings to pick up extra spaces""" if matchobj.group(2): return """<span class="caps">%s</span>""" % matchobj.group(2) else: if matchobj.group(3)[-1] == " ": caps = matchobj.group(3)[:-1] tail = ' ' else: caps = matchobj.group(3) tail = '' return """<span class="caps">%s</span>%s""" % (caps, tail) tags_to_skip_regex = re.compile("<(/)?(?:pre|code|kbd|script|math)[^>]*>", re.IGNORECASE) for token in tokens: if token[0] == "tag": # Don't mess with tags. result.append(token[1]) close_match = tags_to_skip_regex.match(token[1]) if close_match and close_match.group(1) == None: in_skipped_tag = True else: in_skipped_tag = False else: if in_skipped_tag: result.append(token[1]) else: result.append(cap_finder.sub(_cap_wrapper, token[1])) return "".join(result) def number_suffix(text): """Wraps date suffix in <span class="ord"> so they can be styled with CSS. >>> number_suffix("10th") u'10<span class="rod">th</span>' Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't. """ suffix_finder = re.compile(r'(?P<number>[\d]+)(?P<ord>st|nd|rd|th)') def _suffix_process(groups): number = groups.group('number') suffix = groups.group('ord') return "%s<span class='ord'>%s</span>" % (number, suffix) return suffix_finder.sub(_suffix_process, text) def initial_quotes(text): """Wraps initial quotes in ``class="dquo"`` for double quotes or ``class="quo"`` for single quotes. Works in these block tags ``(h1-h6, p, li, dt, dd)`` and also accounts for potential opening inline elements ``a, em, strong, span, b, i`` >>> initial_quotes('"With primes"') u'<span class="dquo">"</span>With primes"' >>> initial_quotes("'With single primes'") u'<span class="quo">\\'</span>With single primes\\'' >>> initial_quotes('<a href="#">"With primes and a link"</a>') u'<a href="#"><span class="dquo">"</span>With primes and a link"</a>' >>> initial_quotes('&#8220;With smartypanted quotes&#8221;') u'<span class="dquo">&#8220;</span>With smartypanted quotes&#8221;' """ quote_finder = re.compile(r"""((<(p|h[1-6]|li|dt|dd)[^>]*>|^) # start with an opening p, h1-6, li, dd, dt or the start of the string \s* # optional white space! (<(a|em|span|strong|i|b)[^>]*>\s*)*) # optional opening inline tags, with more optional white space for each. (("|&ldquo;|&\#8220;)|('|&lsquo;|&\#8216;)) # Find me a quote! (only need to find the left quotes and the primes) # double quotes are in group 7, singles in group 8 """, re.VERBOSE) def _quote_wrapper(matchobj): if matchobj.group(7): classname = "dquo" quote = matchobj.group(7) else: classname = "quo" quote = matchobj.group(8) return """%s<span class="%s">%s</span>""" % (matchobj.group(1), classname, quote) output = quote_finder.sub(_quote_wrapper, text) return output def widont(text): """Replaces the space between the last two words in a string with ``&nbsp;`` Works in these block tags ``(h1-h6, p, li, dd, dt)`` and also accounts for potential closing inline elements ``a, em, strong, span, b, i`` >>> widont('A very simple test') u'A very simple&nbsp;test' Single word items shouldn't be changed >>> widont('Test') u'Test' >>> widont(' Test') u' Test' >>> widont('<ul><li>Test</p></li><ul>') u'<ul><li>Test</p></li><ul>' >>> widont('<ul><li> Test</p></li><ul>') u'<ul><li> Test</p></li><ul>' >>> widont('<p>In a couple of paragraphs</p><p>paragraph two</p>') u'<p>In a couple of&nbsp;paragraphs</p><p>paragraph&nbsp;two</p>' >>> widont('<h1><a href="#">In a link inside a heading</i> </a></h1>') u'<h1><a href="#">In a link inside a&nbsp;heading</i> </a></h1>' >>> widont('<h1><a href="#">In a link</a> followed by other text</h1>') u'<h1><a href="#">In a link</a> followed by other&nbsp;text</h1>' Empty HTMLs shouldn't error >>> widont('<h1><a href="#"></a></h1>') u'<h1><a href="#"></a></h1>' >>> widont('<div>Divs get no love!</div>') u'<div>Divs get no love!</div>' >>> widont('<pre>Neither do PREs</pre>') u'<pre>Neither do PREs</pre>' >>> widont('<div><p>But divs with paragraphs do!</p></div>') u'<div><p>But divs with paragraphs&nbsp;do!</p></div>' """ widont_finder = re.compile(r"""((?:</?(?:a|em|span|strong|i|b)[^>]*>)|[^<>\s]) # must be proceeded by an approved inline opening or closing tag or a nontag/nonspace \s+ # the space to replace ([^<>\s]+ # must be flollowed by non-tag non-space characters \s* # optional white space! (</(a|em|span|strong|i|b)>\s*)* # optional closing inline tags with optional white space after each ((</(p|h[1-6]|li|dt|dd)>)|$)) # end with a closing p, h1-6, li or the end of the string """, re.VERBOSE) output = widont_finder.sub(r'\1&nbsp;\2', text) return output def typogrify(content): """The super typography filter Applies the following filters: widont, smartypants, caps, amp, initial_quotes""" return number_suffix( initial_quotes( caps( smartypants.smartyPants( widont( amp(content)), "2"))))
# [1]: https://github.com/mintchaos/typogrify
random_line_split
typography.py
# -*- encoding: utf-8 -*- # # License: New BSD Style # # [typography.py][1] is a set of filters enhancing written text output. As the # name says, it adds specific typography things documented in the definitions # itself and [smartypants][2]. # # The typography.py filter comes with two options: ``mode`` and ``default``. # ``TYPOGRAPHY_MODE`` sets the `smartypants_attributes` as documented in [2]. # ``default`` (hard-coded) is a list of filters that will be always applied # if *typopgraphy* is invoked + everything you specify in the additional arguments. # # typopgraphy.py offers a custom mode, "a", that don't educate dashes when written # without space like *--bare* or *foo--* using mode "2". # # [1]: https://github.com/mintchaos/typogrify # [2]: http://web.chad.org/projects/smartypants.py/ import re import smartypants from acrylamid.filters import Filter class Typography(Filter): match = [re.compile('^(T|t)ypo(graphy)?$'), 'smartypants'] version = 2 priority = 25.0 def init(self, conf, env): self.mode = conf.get("typography_mode", "2") # -- en-dash, --- em-dash self.default = ['amp', 'widont', 'smartypants', 'caps'] if self.mode == "a": smartypants.educateDashes = new_dashes smartypants.educateDashesOldSchool = new_dashes self.mode = "2" self.ignore = env.options.ignore self.filters = {'amp': amp, 'widont': widont, 'caps': caps, 'initial_quotes': initial_quotes, 'number_suffix': number_suffix, 'typo': typogrify, 'typogrify': typogrify, 'all': typogrify, 'smartypants': smartypants.smartyPants} def transform(self, content, entry, *args): if any(filter(lambda k: k in args, ['all', 'typo', 'typogrify'])): return typogrify(content) for x in ['amp', 'widont', 'smartypants', 'caps', 'initial_quotes', 'number_suffix']: if x in self.default + list(args): if x == 'smartypants': content = self.filters[x](content, self.mode) else: content = self.filters[x](content) return content def new_dashes(str): # patching something-- to return something-- not something&#8212. str = re.sub(r"""(\s)--""", r"""\1&#8211;""", str) # en (yes, backwards) str = re.sub(r"""(\s)---""", r"""\1&#8212;""", str) # em (yes, backwards) return str def amp(text, autoescape=None): """Wraps apersands in HTML with ``<span class="amp">`` so they can be styled with CSS. Apersands are also normalized to ``&amp;``. Requires ampersands to have whitespace or an ``&nbsp;`` on both sides. >>> amp('One & two') u'One <span class="amp">&amp;</span> two' >>> amp('One &amp; two') u'One <span class="amp">&amp;</span> two' >>> amp('One &#38; two') u'One <span class="amp">&amp;</span> two' >>> amp('One&nbsp;&amp;&nbsp;two') u'One&nbsp;<span class="amp">&amp;</span>&nbsp;two' It won't mess up & that are already wrapped, in entities or URLs >>> amp('One <span class="amp">&amp;</span> two') u'One <span class="amp">&amp;</span> two' >>> amp('&ldquo;this&rdquo; & <a href="/?that&amp;test">that</a>') u'&ldquo;this&rdquo; <span class="amp">&amp;</span> <a href="/?that&amp;test">that</a>' It should ignore standalone amps that are in attributes >>> amp('<link href="xyz.html" title="One & Two">xyz</link>') u'<link href="xyz.html" title="One & Two">xyz</link>' """ # tag_pattern from http://haacked.com/archive/2004/10/25/usingregularexpressionstomatchhtml.aspx # it kinda sucks but it fixes the standalone amps in attributes bug tag_pattern = '</?\w+((\s+\w+(\s*=\s*(?:".*?"|\'.*?\'|[^\'">\s]+))?)+\s*|\s*)/?>' amp_finder = re.compile(r"(\s|&nbsp;)(&|&amp;|&\#38;)(\s|&nbsp;)") intra_tag_finder = re.compile(r'(?P<prefix>(%s)?)(?P<text>([^<]*))(?P<suffix>(%s)?)' % (tag_pattern, tag_pattern)) def _amp_process(groups): prefix = groups.group('prefix') or '' text = amp_finder.sub(r"""\1<span class="amp">&amp;</span>\3""", groups.group('text')) suffix = groups.group('suffix') or '' return prefix + text + suffix return intra_tag_finder.sub(_amp_process, text) def caps(text): """Wraps multiple capital letters in ``<span class="caps">`` so they can be styled with CSS. >>> caps("A message from KU") u'A message from <span class="caps">KU</span>' Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't. >>> caps("<PRE>CAPS</pre> more CAPS") u'<PRE>CAPS</pre> more <span class="caps">CAPS</span>' >>> caps("A message from 2KU2 with digits") u'A message from <span class="caps">2KU2</span> with digits' >>> caps("Dotted caps followed by spaces should never include them in the wrap D.O.T. like so.") u'Dotted caps followed by spaces should never include them in the wrap <span class="caps">D.O.T.</span> like so.' All caps with with apostrophes in them shouldn't break. Only handles dump apostrophes though. >>> caps("JIMMY'S") u'<span class="caps">JIMMY\\'S</span>' >>> caps("<i>D.O.T.</i>HE34T<b>RFID</b>") u'<i><span class="caps">D.O.T.</span></i><span class="caps">HE34T</span><b><span class="caps">RFID</span></b>' """ tokens = smartypants._tokenize(text) result = [] in_skipped_tag = False cap_finder = re.compile(r"""( (\b[A-Z\d]* # Group 2: Any amount of caps and digits [A-Z]\d*[A-Z] # A cap string must at least include two caps (but they can have digits between them) [A-Z\d']*\b) # Any amount of caps and digits or dumb apostsrophes | (\b[A-Z]+\.\s? # OR: Group 3: Some caps, followed by a '.' and an optional space (?:[A-Z]+\.\s?)+) # Followed by the same thing at least once more (?:\s|\b|$)) """, re.VERBOSE) def _cap_wrapper(matchobj): """This is necessary to keep dotted cap strings to pick up extra spaces""" if matchobj.group(2): return """<span class="caps">%s</span>""" % matchobj.group(2) else: if matchobj.group(3)[-1] == " ": caps = matchobj.group(3)[:-1] tail = ' ' else: caps = matchobj.group(3) tail = '' return """<span class="caps">%s</span>%s""" % (caps, tail) tags_to_skip_regex = re.compile("<(/)?(?:pre|code|kbd|script|math)[^>]*>", re.IGNORECASE) for token in tokens: if token[0] == "tag": # Don't mess with tags. result.append(token[1]) close_match = tags_to_skip_regex.match(token[1]) if close_match and close_match.group(1) == None: in_skipped_tag = True else: in_skipped_tag = False else: if in_skipped_tag: result.append(token[1]) else: result.append(cap_finder.sub(_cap_wrapper, token[1])) return "".join(result) def number_suffix(text): """Wraps date suffix in <span class="ord"> so they can be styled with CSS. >>> number_suffix("10th") u'10<span class="rod">th</span>' Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't. """ suffix_finder = re.compile(r'(?P<number>[\d]+)(?P<ord>st|nd|rd|th)') def _suffix_process(groups): number = groups.group('number') suffix = groups.group('ord') return "%s<span class='ord'>%s</span>" % (number, suffix) return suffix_finder.sub(_suffix_process, text) def initial_quotes(text): """Wraps initial quotes in ``class="dquo"`` for double quotes or ``class="quo"`` for single quotes. Works in these block tags ``(h1-h6, p, li, dt, dd)`` and also accounts for potential opening inline elements ``a, em, strong, span, b, i`` >>> initial_quotes('"With primes"') u'<span class="dquo">"</span>With primes"' >>> initial_quotes("'With single primes'") u'<span class="quo">\\'</span>With single primes\\'' >>> initial_quotes('<a href="#">"With primes and a link"</a>') u'<a href="#"><span class="dquo">"</span>With primes and a link"</a>' >>> initial_quotes('&#8220;With smartypanted quotes&#8221;') u'<span class="dquo">&#8220;</span>With smartypanted quotes&#8221;' """ quote_finder = re.compile(r"""((<(p|h[1-6]|li|dt|dd)[^>]*>|^) # start with an opening p, h1-6, li, dd, dt or the start of the string \s* # optional white space! (<(a|em|span|strong|i|b)[^>]*>\s*)*) # optional opening inline tags, with more optional white space for each. (("|&ldquo;|&\#8220;)|('|&lsquo;|&\#8216;)) # Find me a quote! (only need to find the left quotes and the primes) # double quotes are in group 7, singles in group 8 """, re.VERBOSE) def _quote_wrapper(matchobj): if matchobj.group(7): classname = "dquo" quote = matchobj.group(7) else:
return """%s<span class="%s">%s</span>""" % (matchobj.group(1), classname, quote) output = quote_finder.sub(_quote_wrapper, text) return output def widont(text): """Replaces the space between the last two words in a string with ``&nbsp;`` Works in these block tags ``(h1-h6, p, li, dd, dt)`` and also accounts for potential closing inline elements ``a, em, strong, span, b, i`` >>> widont('A very simple test') u'A very simple&nbsp;test' Single word items shouldn't be changed >>> widont('Test') u'Test' >>> widont(' Test') u' Test' >>> widont('<ul><li>Test</p></li><ul>') u'<ul><li>Test</p></li><ul>' >>> widont('<ul><li> Test</p></li><ul>') u'<ul><li> Test</p></li><ul>' >>> widont('<p>In a couple of paragraphs</p><p>paragraph two</p>') u'<p>In a couple of&nbsp;paragraphs</p><p>paragraph&nbsp;two</p>' >>> widont('<h1><a href="#">In a link inside a heading</i> </a></h1>') u'<h1><a href="#">In a link inside a&nbsp;heading</i> </a></h1>' >>> widont('<h1><a href="#">In a link</a> followed by other text</h1>') u'<h1><a href="#">In a link</a> followed by other&nbsp;text</h1>' Empty HTMLs shouldn't error >>> widont('<h1><a href="#"></a></h1>') u'<h1><a href="#"></a></h1>' >>> widont('<div>Divs get no love!</div>') u'<div>Divs get no love!</div>' >>> widont('<pre>Neither do PREs</pre>') u'<pre>Neither do PREs</pre>' >>> widont('<div><p>But divs with paragraphs do!</p></div>') u'<div><p>But divs with paragraphs&nbsp;do!</p></div>' """ widont_finder = re.compile(r"""((?:</?(?:a|em|span|strong|i|b)[^>]*>)|[^<>\s]) # must be proceeded by an approved inline opening or closing tag or a nontag/nonspace \s+ # the space to replace ([^<>\s]+ # must be flollowed by non-tag non-space characters \s* # optional white space! (</(a|em|span|strong|i|b)>\s*)* # optional closing inline tags with optional white space after each ((</(p|h[1-6]|li|dt|dd)>)|$)) # end with a closing p, h1-6, li or the end of the string """, re.VERBOSE) output = widont_finder.sub(r'\1&nbsp;\2', text) return output def typogrify(content): """The super typography filter Applies the following filters: widont, smartypants, caps, amp, initial_quotes""" return number_suffix( initial_quotes( caps( smartypants.smartyPants( widont( amp(content)), "2"))))
classname = "quo" quote = matchobj.group(8)
conditional_block
typography.py
# -*- encoding: utf-8 -*- # # License: New BSD Style # # [typography.py][1] is a set of filters enhancing written text output. As the # name says, it adds specific typography things documented in the definitions # itself and [smartypants][2]. # # The typography.py filter comes with two options: ``mode`` and ``default``. # ``TYPOGRAPHY_MODE`` sets the `smartypants_attributes` as documented in [2]. # ``default`` (hard-coded) is a list of filters that will be always applied # if *typopgraphy* is invoked + everything you specify in the additional arguments. # # typopgraphy.py offers a custom mode, "a", that don't educate dashes when written # without space like *--bare* or *foo--* using mode "2". # # [1]: https://github.com/mintchaos/typogrify # [2]: http://web.chad.org/projects/smartypants.py/ import re import smartypants from acrylamid.filters import Filter class Typography(Filter): match = [re.compile('^(T|t)ypo(graphy)?$'), 'smartypants'] version = 2 priority = 25.0 def init(self, conf, env): self.mode = conf.get("typography_mode", "2") # -- en-dash, --- em-dash self.default = ['amp', 'widont', 'smartypants', 'caps'] if self.mode == "a": smartypants.educateDashes = new_dashes smartypants.educateDashesOldSchool = new_dashes self.mode = "2" self.ignore = env.options.ignore self.filters = {'amp': amp, 'widont': widont, 'caps': caps, 'initial_quotes': initial_quotes, 'number_suffix': number_suffix, 'typo': typogrify, 'typogrify': typogrify, 'all': typogrify, 'smartypants': smartypants.smartyPants} def transform(self, content, entry, *args): if any(filter(lambda k: k in args, ['all', 'typo', 'typogrify'])): return typogrify(content) for x in ['amp', 'widont', 'smartypants', 'caps', 'initial_quotes', 'number_suffix']: if x in self.default + list(args): if x == 'smartypants': content = self.filters[x](content, self.mode) else: content = self.filters[x](content) return content def new_dashes(str): # patching something-- to return something-- not something&#8212. str = re.sub(r"""(\s)--""", r"""\1&#8211;""", str) # en (yes, backwards) str = re.sub(r"""(\s)---""", r"""\1&#8212;""", str) # em (yes, backwards) return str def amp(text, autoescape=None):
def caps(text): """Wraps multiple capital letters in ``<span class="caps">`` so they can be styled with CSS. >>> caps("A message from KU") u'A message from <span class="caps">KU</span>' Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't. >>> caps("<PRE>CAPS</pre> more CAPS") u'<PRE>CAPS</pre> more <span class="caps">CAPS</span>' >>> caps("A message from 2KU2 with digits") u'A message from <span class="caps">2KU2</span> with digits' >>> caps("Dotted caps followed by spaces should never include them in the wrap D.O.T. like so.") u'Dotted caps followed by spaces should never include them in the wrap <span class="caps">D.O.T.</span> like so.' All caps with with apostrophes in them shouldn't break. Only handles dump apostrophes though. >>> caps("JIMMY'S") u'<span class="caps">JIMMY\\'S</span>' >>> caps("<i>D.O.T.</i>HE34T<b>RFID</b>") u'<i><span class="caps">D.O.T.</span></i><span class="caps">HE34T</span><b><span class="caps">RFID</span></b>' """ tokens = smartypants._tokenize(text) result = [] in_skipped_tag = False cap_finder = re.compile(r"""( (\b[A-Z\d]* # Group 2: Any amount of caps and digits [A-Z]\d*[A-Z] # A cap string must at least include two caps (but they can have digits between them) [A-Z\d']*\b) # Any amount of caps and digits or dumb apostsrophes | (\b[A-Z]+\.\s? # OR: Group 3: Some caps, followed by a '.' and an optional space (?:[A-Z]+\.\s?)+) # Followed by the same thing at least once more (?:\s|\b|$)) """, re.VERBOSE) def _cap_wrapper(matchobj): """This is necessary to keep dotted cap strings to pick up extra spaces""" if matchobj.group(2): return """<span class="caps">%s</span>""" % matchobj.group(2) else: if matchobj.group(3)[-1] == " ": caps = matchobj.group(3)[:-1] tail = ' ' else: caps = matchobj.group(3) tail = '' return """<span class="caps">%s</span>%s""" % (caps, tail) tags_to_skip_regex = re.compile("<(/)?(?:pre|code|kbd|script|math)[^>]*>", re.IGNORECASE) for token in tokens: if token[0] == "tag": # Don't mess with tags. result.append(token[1]) close_match = tags_to_skip_regex.match(token[1]) if close_match and close_match.group(1) == None: in_skipped_tag = True else: in_skipped_tag = False else: if in_skipped_tag: result.append(token[1]) else: result.append(cap_finder.sub(_cap_wrapper, token[1])) return "".join(result) def number_suffix(text): """Wraps date suffix in <span class="ord"> so they can be styled with CSS. >>> number_suffix("10th") u'10<span class="rod">th</span>' Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't. """ suffix_finder = re.compile(r'(?P<number>[\d]+)(?P<ord>st|nd|rd|th)') def _suffix_process(groups): number = groups.group('number') suffix = groups.group('ord') return "%s<span class='ord'>%s</span>" % (number, suffix) return suffix_finder.sub(_suffix_process, text) def initial_quotes(text): """Wraps initial quotes in ``class="dquo"`` for double quotes or ``class="quo"`` for single quotes. Works in these block tags ``(h1-h6, p, li, dt, dd)`` and also accounts for potential opening inline elements ``a, em, strong, span, b, i`` >>> initial_quotes('"With primes"') u'<span class="dquo">"</span>With primes"' >>> initial_quotes("'With single primes'") u'<span class="quo">\\'</span>With single primes\\'' >>> initial_quotes('<a href="#">"With primes and a link"</a>') u'<a href="#"><span class="dquo">"</span>With primes and a link"</a>' >>> initial_quotes('&#8220;With smartypanted quotes&#8221;') u'<span class="dquo">&#8220;</span>With smartypanted quotes&#8221;' """ quote_finder = re.compile(r"""((<(p|h[1-6]|li|dt|dd)[^>]*>|^) # start with an opening p, h1-6, li, dd, dt or the start of the string \s* # optional white space! (<(a|em|span|strong|i|b)[^>]*>\s*)*) # optional opening inline tags, with more optional white space for each. (("|&ldquo;|&\#8220;)|('|&lsquo;|&\#8216;)) # Find me a quote! (only need to find the left quotes and the primes) # double quotes are in group 7, singles in group 8 """, re.VERBOSE) def _quote_wrapper(matchobj): if matchobj.group(7): classname = "dquo" quote = matchobj.group(7) else: classname = "quo" quote = matchobj.group(8) return """%s<span class="%s">%s</span>""" % (matchobj.group(1), classname, quote) output = quote_finder.sub(_quote_wrapper, text) return output def widont(text): """Replaces the space between the last two words in a string with ``&nbsp;`` Works in these block tags ``(h1-h6, p, li, dd, dt)`` and also accounts for potential closing inline elements ``a, em, strong, span, b, i`` >>> widont('A very simple test') u'A very simple&nbsp;test' Single word items shouldn't be changed >>> widont('Test') u'Test' >>> widont(' Test') u' Test' >>> widont('<ul><li>Test</p></li><ul>') u'<ul><li>Test</p></li><ul>' >>> widont('<ul><li> Test</p></li><ul>') u'<ul><li> Test</p></li><ul>' >>> widont('<p>In a couple of paragraphs</p><p>paragraph two</p>') u'<p>In a couple of&nbsp;paragraphs</p><p>paragraph&nbsp;two</p>' >>> widont('<h1><a href="#">In a link inside a heading</i> </a></h1>') u'<h1><a href="#">In a link inside a&nbsp;heading</i> </a></h1>' >>> widont('<h1><a href="#">In a link</a> followed by other text</h1>') u'<h1><a href="#">In a link</a> followed by other&nbsp;text</h1>' Empty HTMLs shouldn't error >>> widont('<h1><a href="#"></a></h1>') u'<h1><a href="#"></a></h1>' >>> widont('<div>Divs get no love!</div>') u'<div>Divs get no love!</div>' >>> widont('<pre>Neither do PREs</pre>') u'<pre>Neither do PREs</pre>' >>> widont('<div><p>But divs with paragraphs do!</p></div>') u'<div><p>But divs with paragraphs&nbsp;do!</p></div>' """ widont_finder = re.compile(r"""((?:</?(?:a|em|span|strong|i|b)[^>]*>)|[^<>\s]) # must be proceeded by an approved inline opening or closing tag or a nontag/nonspace \s+ # the space to replace ([^<>\s]+ # must be flollowed by non-tag non-space characters \s* # optional white space! (</(a|em|span|strong|i|b)>\s*)* # optional closing inline tags with optional white space after each ((</(p|h[1-6]|li|dt|dd)>)|$)) # end with a closing p, h1-6, li or the end of the string """, re.VERBOSE) output = widont_finder.sub(r'\1&nbsp;\2', text) return output def typogrify(content): """The super typography filter Applies the following filters: widont, smartypants, caps, amp, initial_quotes""" return number_suffix( initial_quotes( caps( smartypants.smartyPants( widont( amp(content)), "2"))))
"""Wraps apersands in HTML with ``<span class="amp">`` so they can be styled with CSS. Apersands are also normalized to ``&amp;``. Requires ampersands to have whitespace or an ``&nbsp;`` on both sides. >>> amp('One & two') u'One <span class="amp">&amp;</span> two' >>> amp('One &amp; two') u'One <span class="amp">&amp;</span> two' >>> amp('One &#38; two') u'One <span class="amp">&amp;</span> two' >>> amp('One&nbsp;&amp;&nbsp;two') u'One&nbsp;<span class="amp">&amp;</span>&nbsp;two' It won't mess up & that are already wrapped, in entities or URLs >>> amp('One <span class="amp">&amp;</span> two') u'One <span class="amp">&amp;</span> two' >>> amp('&ldquo;this&rdquo; & <a href="/?that&amp;test">that</a>') u'&ldquo;this&rdquo; <span class="amp">&amp;</span> <a href="/?that&amp;test">that</a>' It should ignore standalone amps that are in attributes >>> amp('<link href="xyz.html" title="One & Two">xyz</link>') u'<link href="xyz.html" title="One & Two">xyz</link>' """ # tag_pattern from http://haacked.com/archive/2004/10/25/usingregularexpressionstomatchhtml.aspx # it kinda sucks but it fixes the standalone amps in attributes bug tag_pattern = '</?\w+((\s+\w+(\s*=\s*(?:".*?"|\'.*?\'|[^\'">\s]+))?)+\s*|\s*)/?>' amp_finder = re.compile(r"(\s|&nbsp;)(&|&amp;|&\#38;)(\s|&nbsp;)") intra_tag_finder = re.compile(r'(?P<prefix>(%s)?)(?P<text>([^<]*))(?P<suffix>(%s)?)' % (tag_pattern, tag_pattern)) def _amp_process(groups): prefix = groups.group('prefix') or '' text = amp_finder.sub(r"""\1<span class="amp">&amp;</span>\3""", groups.group('text')) suffix = groups.group('suffix') or '' return prefix + text + suffix return intra_tag_finder.sub(_amp_process, text)
identifier_body
typography.py
# -*- encoding: utf-8 -*- # # License: New BSD Style # # [typography.py][1] is a set of filters enhancing written text output. As the # name says, it adds specific typography things documented in the definitions # itself and [smartypants][2]. # # The typography.py filter comes with two options: ``mode`` and ``default``. # ``TYPOGRAPHY_MODE`` sets the `smartypants_attributes` as documented in [2]. # ``default`` (hard-coded) is a list of filters that will be always applied # if *typopgraphy* is invoked + everything you specify in the additional arguments. # # typopgraphy.py offers a custom mode, "a", that don't educate dashes when written # without space like *--bare* or *foo--* using mode "2". # # [1]: https://github.com/mintchaos/typogrify # [2]: http://web.chad.org/projects/smartypants.py/ import re import smartypants from acrylamid.filters import Filter class Typography(Filter): match = [re.compile('^(T|t)ypo(graphy)?$'), 'smartypants'] version = 2 priority = 25.0 def init(self, conf, env): self.mode = conf.get("typography_mode", "2") # -- en-dash, --- em-dash self.default = ['amp', 'widont', 'smartypants', 'caps'] if self.mode == "a": smartypants.educateDashes = new_dashes smartypants.educateDashesOldSchool = new_dashes self.mode = "2" self.ignore = env.options.ignore self.filters = {'amp': amp, 'widont': widont, 'caps': caps, 'initial_quotes': initial_quotes, 'number_suffix': number_suffix, 'typo': typogrify, 'typogrify': typogrify, 'all': typogrify, 'smartypants': smartypants.smartyPants} def transform(self, content, entry, *args): if any(filter(lambda k: k in args, ['all', 'typo', 'typogrify'])): return typogrify(content) for x in ['amp', 'widont', 'smartypants', 'caps', 'initial_quotes', 'number_suffix']: if x in self.default + list(args): if x == 'smartypants': content = self.filters[x](content, self.mode) else: content = self.filters[x](content) return content def new_dashes(str): # patching something-- to return something-- not something&#8212. str = re.sub(r"""(\s)--""", r"""\1&#8211;""", str) # en (yes, backwards) str = re.sub(r"""(\s)---""", r"""\1&#8212;""", str) # em (yes, backwards) return str def amp(text, autoescape=None): """Wraps apersands in HTML with ``<span class="amp">`` so they can be styled with CSS. Apersands are also normalized to ``&amp;``. Requires ampersands to have whitespace or an ``&nbsp;`` on both sides. >>> amp('One & two') u'One <span class="amp">&amp;</span> two' >>> amp('One &amp; two') u'One <span class="amp">&amp;</span> two' >>> amp('One &#38; two') u'One <span class="amp">&amp;</span> two' >>> amp('One&nbsp;&amp;&nbsp;two') u'One&nbsp;<span class="amp">&amp;</span>&nbsp;two' It won't mess up & that are already wrapped, in entities or URLs >>> amp('One <span class="amp">&amp;</span> two') u'One <span class="amp">&amp;</span> two' >>> amp('&ldquo;this&rdquo; & <a href="/?that&amp;test">that</a>') u'&ldquo;this&rdquo; <span class="amp">&amp;</span> <a href="/?that&amp;test">that</a>' It should ignore standalone amps that are in attributes >>> amp('<link href="xyz.html" title="One & Two">xyz</link>') u'<link href="xyz.html" title="One & Two">xyz</link>' """ # tag_pattern from http://haacked.com/archive/2004/10/25/usingregularexpressionstomatchhtml.aspx # it kinda sucks but it fixes the standalone amps in attributes bug tag_pattern = '</?\w+((\s+\w+(\s*=\s*(?:".*?"|\'.*?\'|[^\'">\s]+))?)+\s*|\s*)/?>' amp_finder = re.compile(r"(\s|&nbsp;)(&|&amp;|&\#38;)(\s|&nbsp;)") intra_tag_finder = re.compile(r'(?P<prefix>(%s)?)(?P<text>([^<]*))(?P<suffix>(%s)?)' % (tag_pattern, tag_pattern)) def _amp_process(groups): prefix = groups.group('prefix') or '' text = amp_finder.sub(r"""\1<span class="amp">&amp;</span>\3""", groups.group('text')) suffix = groups.group('suffix') or '' return prefix + text + suffix return intra_tag_finder.sub(_amp_process, text) def caps(text): """Wraps multiple capital letters in ``<span class="caps">`` so they can be styled with CSS. >>> caps("A message from KU") u'A message from <span class="caps">KU</span>' Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't. >>> caps("<PRE>CAPS</pre> more CAPS") u'<PRE>CAPS</pre> more <span class="caps">CAPS</span>' >>> caps("A message from 2KU2 with digits") u'A message from <span class="caps">2KU2</span> with digits' >>> caps("Dotted caps followed by spaces should never include them in the wrap D.O.T. like so.") u'Dotted caps followed by spaces should never include them in the wrap <span class="caps">D.O.T.</span> like so.' All caps with with apostrophes in them shouldn't break. Only handles dump apostrophes though. >>> caps("JIMMY'S") u'<span class="caps">JIMMY\\'S</span>' >>> caps("<i>D.O.T.</i>HE34T<b>RFID</b>") u'<i><span class="caps">D.O.T.</span></i><span class="caps">HE34T</span><b><span class="caps">RFID</span></b>' """ tokens = smartypants._tokenize(text) result = [] in_skipped_tag = False cap_finder = re.compile(r"""( (\b[A-Z\d]* # Group 2: Any amount of caps and digits [A-Z]\d*[A-Z] # A cap string must at least include two caps (but they can have digits between them) [A-Z\d']*\b) # Any amount of caps and digits or dumb apostsrophes | (\b[A-Z]+\.\s? # OR: Group 3: Some caps, followed by a '.' and an optional space (?:[A-Z]+\.\s?)+) # Followed by the same thing at least once more (?:\s|\b|$)) """, re.VERBOSE) def _cap_wrapper(matchobj): """This is necessary to keep dotted cap strings to pick up extra spaces""" if matchobj.group(2): return """<span class="caps">%s</span>""" % matchobj.group(2) else: if matchobj.group(3)[-1] == " ": caps = matchobj.group(3)[:-1] tail = ' ' else: caps = matchobj.group(3) tail = '' return """<span class="caps">%s</span>%s""" % (caps, tail) tags_to_skip_regex = re.compile("<(/)?(?:pre|code|kbd|script|math)[^>]*>", re.IGNORECASE) for token in tokens: if token[0] == "tag": # Don't mess with tags. result.append(token[1]) close_match = tags_to_skip_regex.match(token[1]) if close_match and close_match.group(1) == None: in_skipped_tag = True else: in_skipped_tag = False else: if in_skipped_tag: result.append(token[1]) else: result.append(cap_finder.sub(_cap_wrapper, token[1])) return "".join(result) def number_suffix(text): """Wraps date suffix in <span class="ord"> so they can be styled with CSS. >>> number_suffix("10th") u'10<span class="rod">th</span>' Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't. """ suffix_finder = re.compile(r'(?P<number>[\d]+)(?P<ord>st|nd|rd|th)') def _suffix_process(groups): number = groups.group('number') suffix = groups.group('ord') return "%s<span class='ord'>%s</span>" % (number, suffix) return suffix_finder.sub(_suffix_process, text) def initial_quotes(text): """Wraps initial quotes in ``class="dquo"`` for double quotes or ``class="quo"`` for single quotes. Works in these block tags ``(h1-h6, p, li, dt, dd)`` and also accounts for potential opening inline elements ``a, em, strong, span, b, i`` >>> initial_quotes('"With primes"') u'<span class="dquo">"</span>With primes"' >>> initial_quotes("'With single primes'") u'<span class="quo">\\'</span>With single primes\\'' >>> initial_quotes('<a href="#">"With primes and a link"</a>') u'<a href="#"><span class="dquo">"</span>With primes and a link"</a>' >>> initial_quotes('&#8220;With smartypanted quotes&#8221;') u'<span class="dquo">&#8220;</span>With smartypanted quotes&#8221;' """ quote_finder = re.compile(r"""((<(p|h[1-6]|li|dt|dd)[^>]*>|^) # start with an opening p, h1-6, li, dd, dt or the start of the string \s* # optional white space! (<(a|em|span|strong|i|b)[^>]*>\s*)*) # optional opening inline tags, with more optional white space for each. (("|&ldquo;|&\#8220;)|('|&lsquo;|&\#8216;)) # Find me a quote! (only need to find the left quotes and the primes) # double quotes are in group 7, singles in group 8 """, re.VERBOSE) def _quote_wrapper(matchobj): if matchobj.group(7): classname = "dquo" quote = matchobj.group(7) else: classname = "quo" quote = matchobj.group(8) return """%s<span class="%s">%s</span>""" % (matchobj.group(1), classname, quote) output = quote_finder.sub(_quote_wrapper, text) return output def widont(text): """Replaces the space between the last two words in a string with ``&nbsp;`` Works in these block tags ``(h1-h6, p, li, dd, dt)`` and also accounts for potential closing inline elements ``a, em, strong, span, b, i`` >>> widont('A very simple test') u'A very simple&nbsp;test' Single word items shouldn't be changed >>> widont('Test') u'Test' >>> widont(' Test') u' Test' >>> widont('<ul><li>Test</p></li><ul>') u'<ul><li>Test</p></li><ul>' >>> widont('<ul><li> Test</p></li><ul>') u'<ul><li> Test</p></li><ul>' >>> widont('<p>In a couple of paragraphs</p><p>paragraph two</p>') u'<p>In a couple of&nbsp;paragraphs</p><p>paragraph&nbsp;two</p>' >>> widont('<h1><a href="#">In a link inside a heading</i> </a></h1>') u'<h1><a href="#">In a link inside a&nbsp;heading</i> </a></h1>' >>> widont('<h1><a href="#">In a link</a> followed by other text</h1>') u'<h1><a href="#">In a link</a> followed by other&nbsp;text</h1>' Empty HTMLs shouldn't error >>> widont('<h1><a href="#"></a></h1>') u'<h1><a href="#"></a></h1>' >>> widont('<div>Divs get no love!</div>') u'<div>Divs get no love!</div>' >>> widont('<pre>Neither do PREs</pre>') u'<pre>Neither do PREs</pre>' >>> widont('<div><p>But divs with paragraphs do!</p></div>') u'<div><p>But divs with paragraphs&nbsp;do!</p></div>' """ widont_finder = re.compile(r"""((?:</?(?:a|em|span|strong|i|b)[^>]*>)|[^<>\s]) # must be proceeded by an approved inline opening or closing tag or a nontag/nonspace \s+ # the space to replace ([^<>\s]+ # must be flollowed by non-tag non-space characters \s* # optional white space! (</(a|em|span|strong|i|b)>\s*)* # optional closing inline tags with optional white space after each ((</(p|h[1-6]|li|dt|dd)>)|$)) # end with a closing p, h1-6, li or the end of the string """, re.VERBOSE) output = widont_finder.sub(r'\1&nbsp;\2', text) return output def
(content): """The super typography filter Applies the following filters: widont, smartypants, caps, amp, initial_quotes""" return number_suffix( initial_quotes( caps( smartypants.smartyPants( widont( amp(content)), "2"))))
typogrify
identifier_name
indent_list_item.py
import re import sublime import sublime_plugin class IndentListItemCommand(sublime_plugin.TextCommand): bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))' bullet_pattern_re = re.compile(bullet_pattern) line_pattern_re = re.compile(r'^\s*' + bullet_pattern) spaces_re = re.compile(r'^\s*') def run(self, edit, reverse=False): for region in self.view.sel(): if region.a != region.b: continue line = self.view.line(region) line_content = self.view.substr(line) new_line = line_content m = self.line_pattern_re.match(new_line) if not m: return # Determine how to indent (tab or spaces) tab_str = self.view.settings().get('tab_size', 4) * ' ' sep_str = ' ' if m.group(4) else '' prev_line = self.view.line(sublime.Region(line.begin() - 1, line.begin() - 1)) prev_line_content = self.view.substr(prev_line) prev_prev_line = self.view.line(sublime.Region(prev_line.begin() - 1, prev_line.begin() - 1)) prev_prev_line_content = self.view.substr(prev_prev_line) if not reverse: # Do the indentation new_line = self.bullet_pattern_re.sub(tab_str + sep_str + r'\1', new_line) # Insert the new item if prev_line_content: new_line = '\n' + new_line else:
endings = ['.', ')'] # Transform the bullet to the next/previous bullet type if self.view.settings().get('list_indent_auto_switch_bullet', True): bullets = self.view.settings().get('list_indent_bullets', ['*', '-', '+']) def change_bullet(m): bullet = m.group(1) try: return bullets[(bullets.index(bullet) + (1 if not reverse else -1)) % len(bullets)] except ValueError: pass n = m.group(2) ending = endings[(endings.index(m.group(4)) + (1 if not reverse else -1)) % len(endings)] if n.isdigit(): return '${1:a}' + ending elif n != '#': return '${1:0}' + ending return m.group(2) + ending new_line = self.bullet_pattern_re.sub(change_bullet, new_line) self.view.replace(edit, line, '') self.view.run_command('insert_snippet', {'contents': new_line}) def is_enabled(self): return bool(self.view.score_selector(self.view.sel()[0].a, 'text.restructuredtext'))
if not new_line.startswith(tab_str): continue # Do the unindentation new_line = re.sub(tab_str + sep_str + self.bullet_pattern, r'\1', new_line) # Insert the new item if prev_line_content: new_line = '\n' + new_line else: prev_spaces = self.spaces_re.match(prev_prev_line_content).group(0) spaces = self.spaces_re.match(new_line).group(0) if prev_spaces == spaces: line = sublime.Region(line.begin() - 1, line.end())
conditional_block
indent_list_item.py
import re import sublime import sublime_plugin class IndentListItemCommand(sublime_plugin.TextCommand): bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))' bullet_pattern_re = re.compile(bullet_pattern) line_pattern_re = re.compile(r'^\s*' + bullet_pattern) spaces_re = re.compile(r'^\s*') def run(self, edit, reverse=False): for region in self.view.sel(): if region.a != region.b: continue line = self.view.line(region) line_content = self.view.substr(line) new_line = line_content m = self.line_pattern_re.match(new_line) if not m: return # Determine how to indent (tab or spaces) tab_str = self.view.settings().get('tab_size', 4) * ' ' sep_str = ' ' if m.group(4) else '' prev_line = self.view.line(sublime.Region(line.begin() - 1, line.begin() - 1)) prev_line_content = self.view.substr(prev_line) prev_prev_line = self.view.line(sublime.Region(prev_line.begin() - 1, prev_line.begin() - 1)) prev_prev_line_content = self.view.substr(prev_prev_line) if not reverse: # Do the indentation new_line = self.bullet_pattern_re.sub(tab_str + sep_str + r'\1', new_line)
else: if not new_line.startswith(tab_str): continue # Do the unindentation new_line = re.sub(tab_str + sep_str + self.bullet_pattern, r'\1', new_line) # Insert the new item if prev_line_content: new_line = '\n' + new_line else: prev_spaces = self.spaces_re.match(prev_prev_line_content).group(0) spaces = self.spaces_re.match(new_line).group(0) if prev_spaces == spaces: line = sublime.Region(line.begin() - 1, line.end()) endings = ['.', ')'] # Transform the bullet to the next/previous bullet type if self.view.settings().get('list_indent_auto_switch_bullet', True): bullets = self.view.settings().get('list_indent_bullets', ['*', '-', '+']) def change_bullet(m): bullet = m.group(1) try: return bullets[(bullets.index(bullet) + (1 if not reverse else -1)) % len(bullets)] except ValueError: pass n = m.group(2) ending = endings[(endings.index(m.group(4)) + (1 if not reverse else -1)) % len(endings)] if n.isdigit(): return '${1:a}' + ending elif n != '#': return '${1:0}' + ending return m.group(2) + ending new_line = self.bullet_pattern_re.sub(change_bullet, new_line) self.view.replace(edit, line, '') self.view.run_command('insert_snippet', {'contents': new_line}) def is_enabled(self): return bool(self.view.score_selector(self.view.sel()[0].a, 'text.restructuredtext'))
# Insert the new item if prev_line_content: new_line = '\n' + new_line
random_line_split
indent_list_item.py
import re import sublime import sublime_plugin class IndentListItemCommand(sublime_plugin.TextCommand):
bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))' bullet_pattern_re = re.compile(bullet_pattern) line_pattern_re = re.compile(r'^\s*' + bullet_pattern) spaces_re = re.compile(r'^\s*') def run(self, edit, reverse=False): for region in self.view.sel(): if region.a != region.b: continue line = self.view.line(region) line_content = self.view.substr(line) new_line = line_content m = self.line_pattern_re.match(new_line) if not m: return # Determine how to indent (tab or spaces) tab_str = self.view.settings().get('tab_size', 4) * ' ' sep_str = ' ' if m.group(4) else '' prev_line = self.view.line(sublime.Region(line.begin() - 1, line.begin() - 1)) prev_line_content = self.view.substr(prev_line) prev_prev_line = self.view.line(sublime.Region(prev_line.begin() - 1, prev_line.begin() - 1)) prev_prev_line_content = self.view.substr(prev_prev_line) if not reverse: # Do the indentation new_line = self.bullet_pattern_re.sub(tab_str + sep_str + r'\1', new_line) # Insert the new item if prev_line_content: new_line = '\n' + new_line else: if not new_line.startswith(tab_str): continue # Do the unindentation new_line = re.sub(tab_str + sep_str + self.bullet_pattern, r'\1', new_line) # Insert the new item if prev_line_content: new_line = '\n' + new_line else: prev_spaces = self.spaces_re.match(prev_prev_line_content).group(0) spaces = self.spaces_re.match(new_line).group(0) if prev_spaces == spaces: line = sublime.Region(line.begin() - 1, line.end()) endings = ['.', ')'] # Transform the bullet to the next/previous bullet type if self.view.settings().get('list_indent_auto_switch_bullet', True): bullets = self.view.settings().get('list_indent_bullets', ['*', '-', '+']) def change_bullet(m): bullet = m.group(1) try: return bullets[(bullets.index(bullet) + (1 if not reverse else -1)) % len(bullets)] except ValueError: pass n = m.group(2) ending = endings[(endings.index(m.group(4)) + (1 if not reverse else -1)) % len(endings)] if n.isdigit(): return '${1:a}' + ending elif n != '#': return '${1:0}' + ending return m.group(2) + ending new_line = self.bullet_pattern_re.sub(change_bullet, new_line) self.view.replace(edit, line, '') self.view.run_command('insert_snippet', {'contents': new_line}) def is_enabled(self): return bool(self.view.score_selector(self.view.sel()[0].a, 'text.restructuredtext'))
identifier_body
indent_list_item.py
import re import sublime import sublime_plugin class IndentListItemCommand(sublime_plugin.TextCommand): bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))' bullet_pattern_re = re.compile(bullet_pattern) line_pattern_re = re.compile(r'^\s*' + bullet_pattern) spaces_re = re.compile(r'^\s*') def run(self, edit, reverse=False): for region in self.view.sel(): if region.a != region.b: continue line = self.view.line(region) line_content = self.view.substr(line) new_line = line_content m = self.line_pattern_re.match(new_line) if not m: return # Determine how to indent (tab or spaces) tab_str = self.view.settings().get('tab_size', 4) * ' ' sep_str = ' ' if m.group(4) else '' prev_line = self.view.line(sublime.Region(line.begin() - 1, line.begin() - 1)) prev_line_content = self.view.substr(prev_line) prev_prev_line = self.view.line(sublime.Region(prev_line.begin() - 1, prev_line.begin() - 1)) prev_prev_line_content = self.view.substr(prev_prev_line) if not reverse: # Do the indentation new_line = self.bullet_pattern_re.sub(tab_str + sep_str + r'\1', new_line) # Insert the new item if prev_line_content: new_line = '\n' + new_line else: if not new_line.startswith(tab_str): continue # Do the unindentation new_line = re.sub(tab_str + sep_str + self.bullet_pattern, r'\1', new_line) # Insert the new item if prev_line_content: new_line = '\n' + new_line else: prev_spaces = self.spaces_re.match(prev_prev_line_content).group(0) spaces = self.spaces_re.match(new_line).group(0) if prev_spaces == spaces: line = sublime.Region(line.begin() - 1, line.end()) endings = ['.', ')'] # Transform the bullet to the next/previous bullet type if self.view.settings().get('list_indent_auto_switch_bullet', True): bullets = self.view.settings().get('list_indent_bullets', ['*', '-', '+']) def change_bullet(m): bullet = m.group(1) try: return bullets[(bullets.index(bullet) + (1 if not reverse else -1)) % len(bullets)] except ValueError: pass n = m.group(2) ending = endings[(endings.index(m.group(4)) + (1 if not reverse else -1)) % len(endings)] if n.isdigit(): return '${1:a}' + ending elif n != '#': return '${1:0}' + ending return m.group(2) + ending new_line = self.bullet_pattern_re.sub(change_bullet, new_line) self.view.replace(edit, line, '') self.view.run_command('insert_snippet', {'contents': new_line}) def
(self): return bool(self.view.score_selector(self.view.sel()[0].a, 'text.restructuredtext'))
is_enabled
identifier_name
bpmn2xpdl20-min.js
if(!ORYX.Plugins)
ORYX.Plugins.BPMN2XPDL20=ORYX.Plugins.AbstractPlugin.extend({construct:function(){arguments.callee.$.construct.apply(this,arguments); this.facade.offer({name:ORYX.I18N.BPMN2XPDL.xpdlExport,functionality:this.transform.bind(this),group:ORYX.I18N.BPMN2XPDL.group,dropDownGroupIcon:ORYX.BASE_FILE_PATH+"images/export2.png",icon:ORYX.BASE_FILE_PATH+"images/page_white_gear.png",description:ORYX.I18N.BPMN2XPDL.xpdlExport,index:1,minShape:0,maxShape:0}); this.facade.offer({name:ORYX.I18N.BPMN2XPDL.xpdlImport,functionality:this.importXPDL.bind(this),group:ORYX.I18N.BPMN2XPDL.group,dropDownGroupIcon:ORYX.BASE_FILE_PATH+"images/import.png",icon:ORYX.BASE_FILE_PATH+"images/page_white_gear.png",description:ORYX.I18N.BPMN2XPDL.xpdlImport,index:1,minShape:0,maxShape:0}) },transform:function(){var a=ORYX.CONFIG.BPMN2XPDLPATH; var b=this.facade.getSerializedJSON(); Ext.Ajax.request({url:a,method:"POST",success:function(c){this.openDownloadWindow(window.document.title+".xml",c.responseText) }.bind(this),failure:function(){Ext.Msg.alert("Conversion failed") },params:{data:b,action:"Export"}}) },importXPDL:function(a){var b=ORYX.CONFIG.BPMN2XPDLPATH; var d=new Ext.form.FormPanel({baseCls:"x-plain",labelWidth:50,defaultType:"textfield",items:[{text:ORYX.I18N.BPMN2XPDL.selectFile,style:"font-size:12px;margin-bottom:10px;display:block;",anchor:"100%",xtype:"label"},{fieldLabel:ORYX.I18N.BPMN2XPDL.file,name:"subject",inputType:"file",style:"margin-bottom:10px;display:block;",itemCls:"ext_specific_window_overflow"},{xtype:"textarea",hideLabel:true,name:"msg",anchor:"100% -63"}]}); var c=new Ext.Window({autoCreate:true,layout:"fit",plain:true,bodyStyle:"padding:5px;",title:ORYX.I18N.BPMN2XPDL.impXPDL,height:350,width:500,modal:true,fixedcenter:true,shadow:true,proxyDrag:true,resizable:true,items:[d],buttons:[{text:ORYX.I18N.BPMN2XPDL.impBtn,handler:function(){var e=new Ext.LoadMask(Ext.getBody(),{msg:ORYX.I18N.BPMN2XPDL.impProgress}); e.show(); window.setTimeout(function(){var f=d.items.items[2].getValue(); Ext.Ajax.request({url:b,method:"POST",success:function(g){this.facade.importJSON(g.responseText); e.hide(); c.hide() }.bind(this),failure:function(){e.hide(); Ext.Msg.alert("Import failed") },params:{data:f,action:"Import"}}) }.bind(this),100) }.bind(this)},{text:ORYX.I18N.BPMN2XPDL.close,handler:function(){c.hide() }.bind(this)}]}); c.on("hide",function(){c.destroy(true); delete c }); c.show(); d.items.items[1].getEl().dom.addEventListener("change",function(e){var f=e.target.files[0].getAsText("UTF-8"); d.items.items[2].setValue(f) },true) }});
{ORYX.Plugins=new Object() }
conditional_block
bpmn2xpdl20-min.js
if(!ORYX.Plugins){ORYX.Plugins=new Object() }ORYX.Plugins.BPMN2XPDL20=ORYX.Plugins.AbstractPlugin.extend({construct:function(){arguments.callee.$.construct.apply(this,arguments); this.facade.offer({name:ORYX.I18N.BPMN2XPDL.xpdlExport,functionality:this.transform.bind(this),group:ORYX.I18N.BPMN2XPDL.group,dropDownGroupIcon:ORYX.BASE_FILE_PATH+"images/export2.png",icon:ORYX.BASE_FILE_PATH+"images/page_white_gear.png",description:ORYX.I18N.BPMN2XPDL.xpdlExport,index:1,minShape:0,maxShape:0}); this.facade.offer({name:ORYX.I18N.BPMN2XPDL.xpdlImport,functionality:this.importXPDL.bind(this),group:ORYX.I18N.BPMN2XPDL.group,dropDownGroupIcon:ORYX.BASE_FILE_PATH+"images/import.png",icon:ORYX.BASE_FILE_PATH+"images/page_white_gear.png",description:ORYX.I18N.BPMN2XPDL.xpdlImport,index:1,minShape:0,maxShape:0}) },transform:function(){var a=ORYX.CONFIG.BPMN2XPDLPATH; var b=this.facade.getSerializedJSON(); Ext.Ajax.request({url:a,method:"POST",success:function(c){this.openDownloadWindow(window.document.title+".xml",c.responseText) }.bind(this),failure:function(){Ext.Msg.alert("Conversion failed") },params:{data:b,action:"Export"}}) },importXPDL:function(a){var b=ORYX.CONFIG.BPMN2XPDLPATH; var d=new Ext.form.FormPanel({baseCls:"x-plain",labelWidth:50,defaultType:"textfield",items:[{text:ORYX.I18N.BPMN2XPDL.selectFile,style:"font-size:12px;margin-bottom:10px;display:block;",anchor:"100%",xtype:"label"},{fieldLabel:ORYX.I18N.BPMN2XPDL.file,name:"subject",inputType:"file",style:"margin-bottom:10px;display:block;",itemCls:"ext_specific_window_overflow"},{xtype:"textarea",hideLabel:true,name:"msg",anchor:"100% -63"}]}); var c=new Ext.Window({autoCreate:true,layout:"fit",plain:true,bodyStyle:"padding:5px;",title:ORYX.I18N.BPMN2XPDL.impXPDL,height:350,width:500,modal:true,fixedcenter:true,shadow:true,proxyDrag:true,resizable:true,items:[d],buttons:[{text:ORYX.I18N.BPMN2XPDL.impBtn,handler:function(){var e=new Ext.LoadMask(Ext.getBody(),{msg:ORYX.I18N.BPMN2XPDL.impProgress}); e.show(); window.setTimeout(function(){var f=d.items.items[2].getValue(); Ext.Ajax.request({url:b,method:"POST",success:function(g){this.facade.importJSON(g.responseText); e.hide(); c.hide() }.bind(this),failure:function(){e.hide(); Ext.Msg.alert("Import failed") },params:{data:f,action:"Import"}}) }.bind(this),100) }.bind(this)},{text:ORYX.I18N.BPMN2XPDL.close,handler:function(){c.hide() }.bind(this)}]}); c.on("hide",function(){c.destroy(true); delete c }); c.show(); d.items.items[1].getEl().dom.addEventListener("change",function(e){var f=e.target.files[0].getAsText("UTF-8");
}});
d.items.items[2].setValue(f) },true)
random_line_split
App.js
import React, { useState } from 'react'; import ReactNodeGraph from '../index'; const exampleGraph = { "nodes":[ {"nid":1,"type":"WebGLRenderer","x":1479,"y":351,"fields":{"in":[{"name":"width"},{"name":"height"},{"name":"scene"},{"name":"camera"},{"name":"bg_color"},{"name":"postfx"},{"name":"shadowCameraNear"},{"name":"shadowCameraFar"},{"name":"shadowMapWidth"},{"name":"shadowMapHeight"},{"name":"shadowMapEnabled"},{"name":"shadowMapSoft"}],"out":[]}}, {"nid":14,"type":"Camera","x":549,"y":478,"fields":{"in":[{"name":"fov"},{"name":"aspect"},{"name":"near"},{"name":"far"},{"name":"position"},{"name":"target"},{"name":"useTarget"}],"out":[{"name":"out"}]}}, {"nid":23,"type":"Scene","x":1216,"y":217,"fields":{"in":[{"name":"children"},{"name":"position"},{"name":"rotation"},{"name":"scale"},{"name":"doubleSided"},{"name":"visible"},{"name":"castShadow"},{"name":"receiveShadow"}],"out":[{"name":"out"}]}}, {"nid":35,"type":"Merge","x":948,"y":217,"fields":{"in":[{"name":"in0"},{"name":"in1"},{"name":"in2"},{"name":"in3"},{"name":"in4"},{"name":"in5"}],"out":[{"name":"out"}]}}, {"nid":45,"type":"Color","x":950,"y":484,"fields":{"in":[{"name":"rgb"},{"name":"r"},{"name":"g"},{"name":"b"}],"out":[{"name":"rgb"},{"name":"r"},{"name":"g"},{"name":"b"}]}}, {"nid":55,"type":"Vector3","x":279,"y":503,"fields":{"in":[{"name":"xyz"},{"name":"x"},{"name":"y"},{"name":"z"}],"out":[{"name":"xyz"},{"name":"x"},{"name":"y"},{"name":"z"}]}}, {"nid":65,"type":"ThreeMesh","x":707,"y":192,"fields":{"in":[{"name":"children"},{"name":"position"},{"name":"rotation"},{"name":"scale"},{"name":"doubleSided"},{"name":"visible"},{"name":"castShadow"},{"name":"receiveShadow"},{"name":"geometry"},{"name":"material"},{"name":"overdraw"}],"out":[{"name":"out"}]}}, {"nid":79,"type":"Timer","x":89,"y":82,"fields":{"in":[{"name":"reset"},{"name":"pause"},{"name":"max"}],"out":[{"name":"out"}]}}, {"nid":84,"type":"MathMult","x":284,"y":82,"fields":{"in":[{"name":"in"},{"name":"factor"}],"out":[{"name":"out"}]}}, {"nid":89,"type":"Vector3","x":486,"y":188,"fields":{"in":[{"name":"xyz"},{"name":"x"},{"name":"y"},{"name":"z"}],"out":[{"name":"xyz"},{"name":"x"},{"name":"y"},{"name":"z"}]}} ], "connections":[ {"from_node":23,"from":"out","to_node":1,"to":"scene"}, {"from_node":14,"from":"out","to_node":1,"to":"camera"}, {"from_node":14,"from":"out","to_node":35,"to":"in5"}, {"from_node":35,"from":"out","to_node":23,"to":"children"}, {"from_node":45,"from":"rgb","to_node":1,"to":"bg_color"}, {"from_node":55,"from":"xyz","to_node":14,"to":"position"}, {"from_node":65,"from":"out","to_node":35,"to":"in0"}, {"from_node":79,"from":"out","to_node":84,"to":"in"}, {"from_node":89,"from":"xyz","to_node":65,"to":"rotation"}, {"from_node":84,"from":"out","to_node":89,"to":"y"} ] }; export const App = () => { const [state, setState] = useState(exampleGraph); const onNewConnector = (fromNode, fromPin, toNode, toPin) => { let connections = [...state.connections, { from_node: fromNode, from: fromPin, to_node: toNode, to: toPin }]; console.log({...state, ...connections}); setState(old => { return { ...old, "connections": connections } }); } const onRemoveConnector = (connector) => { let connections = [...state.connections]; connections = connections.filter(connection => { return connection !== connector; }); setState(old => { return { ...old,
}); } const onNodeMove = (nid, pos) => { console.log(`end move:`, nid, pos); } const onNodeStartMove = nid => { console.log(`start move:`, nid); } const handleNodeSelect = nid => { console.log(`node selected:`, nid); } const handleNodeDeselect = nid => { console.log(`node deselected:`, nid); } return <ReactNodeGraph data={state} onNodeMove={(nid, pos) => onNodeMove(nid, pos)} onNodeStartMove={nid => onNodeStartMove(nid)} onNewConnector={(n1, o, n2, i) => onNewConnector(n1, o, n2, i)} onRemoveConnector={connector => onRemoveConnector(connector)} onNodeSelect={nid => handleNodeSelect(nid)} onNodeDeselect={nid => handleNodeDeselect(nid)} />; } export default App;
"connections": connections }
random_line_split
create_org_data_czar_policy.py
""" create_org_data_czar_policy.py Creates an IAM group for an edX org and applies an S3 policy to that group that allows for read-only access to the group. """ import argparse import boto3 from botocore.exceptions import ClientError from string import Template import sys template = Template("""{ "Version":"2012-10-17", "Statement": [ { "Sid": "AllowListingOfOrgFolder", "Action": ["s3:ListBucket"], "Effect": "Allow", "Resource": ["arn:aws:s3:::edx-course-data"], "Condition":{"StringLike":{"s3:prefix":["$org","$org/*"]}} }, { "Sid": "AllowGetBucketLocation", "Action": ["s3:GetBucketLocation"], "Effect": "Allow", "Resource": ["arn:aws:s3:::edx-course-data"] }, { "Sid": "AllowGetS3ActionInOrgFolder", "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::edx-course-data/$org/*"] } ] }""") def add_org_group(org, iam_connection): group_name = "edx-course-data-{org}".format(org=org) try: iam_connection.create_group(GroupName=group_name) except ClientError as bse: if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else: print(bse) try: iam_connection.put_group_policy( GroupName=group_name, PolicyName=group_name, PolicyDocument=template.substitute(org=org) ) except boto.exception.BotoServerError as bse: if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else:
parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-o', '--org', help='Name of the org for which to create an IAM ' 'role and policy, this should have the same ' 'name as the S3 bucket') group.add_argument('-f', '--file', help='The path to a file containing one org name ' 'per line.') args = parser.parse_args() iam_connection = boto3.client('iam') if args.org: add_org_group(args.org.rstrip('\n').lower(), iam_connection) elif args.file: with open(args.file) as file: for line in file: org = line.rstrip('\n').lower() add_org_group(org, iam_connection) else: parser.print_usage() sys.exit(1) sys.exit(0)
print(bse) print(template.substitute(org=org))
conditional_block
create_org_data_czar_policy.py
""" create_org_data_czar_policy.py Creates an IAM group for an edX org and applies an S3 policy to that group that allows for read-only access to the group. """ import argparse import boto3 from botocore.exceptions import ClientError from string import Template import sys template = Template("""{ "Version":"2012-10-17", "Statement": [ { "Sid": "AllowListingOfOrgFolder", "Action": ["s3:ListBucket"], "Effect": "Allow", "Resource": ["arn:aws:s3:::edx-course-data"], "Condition":{"StringLike":{"s3:prefix":["$org","$org/*"]}} }, { "Sid": "AllowGetBucketLocation", "Action": ["s3:GetBucketLocation"], "Effect": "Allow", "Resource": ["arn:aws:s3:::edx-course-data"] }, { "Sid": "AllowGetS3ActionInOrgFolder", "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::edx-course-data/$org/*"] } ] }""") def
(org, iam_connection): group_name = "edx-course-data-{org}".format(org=org) try: iam_connection.create_group(GroupName=group_name) except ClientError as bse: if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else: print(bse) try: iam_connection.put_group_policy( GroupName=group_name, PolicyName=group_name, PolicyDocument=template.substitute(org=org) ) except boto.exception.BotoServerError as bse: if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else: print(bse) print(template.substitute(org=org)) parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-o', '--org', help='Name of the org for which to create an IAM ' 'role and policy, this should have the same ' 'name as the S3 bucket') group.add_argument('-f', '--file', help='The path to a file containing one org name ' 'per line.') args = parser.parse_args() iam_connection = boto3.client('iam') if args.org: add_org_group(args.org.rstrip('\n').lower(), iam_connection) elif args.file: with open(args.file) as file: for line in file: org = line.rstrip('\n').lower() add_org_group(org, iam_connection) else: parser.print_usage() sys.exit(1) sys.exit(0)
add_org_group
identifier_name
create_org_data_czar_policy.py
""" create_org_data_czar_policy.py Creates an IAM group for an edX org and applies an S3 policy to that group that allows for read-only access to the group. """ import argparse import boto3 from botocore.exceptions import ClientError from string import Template import sys template = Template("""{ "Version":"2012-10-17", "Statement": [ { "Sid": "AllowListingOfOrgFolder", "Action": ["s3:ListBucket"], "Effect": "Allow", "Resource": ["arn:aws:s3:::edx-course-data"], "Condition":{"StringLike":{"s3:prefix":["$org","$org/*"]}} }, { "Sid": "AllowGetBucketLocation", "Action": ["s3:GetBucketLocation"], "Effect": "Allow", "Resource": ["arn:aws:s3:::edx-course-data"] }, { "Sid": "AllowGetS3ActionInOrgFolder", "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::edx-course-data/$org/*"] } ] }""") def add_org_group(org, iam_connection):
parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-o', '--org', help='Name of the org for which to create an IAM ' 'role and policy, this should have the same ' 'name as the S3 bucket') group.add_argument('-f', '--file', help='The path to a file containing one org name ' 'per line.') args = parser.parse_args() iam_connection = boto3.client('iam') if args.org: add_org_group(args.org.rstrip('\n').lower(), iam_connection) elif args.file: with open(args.file) as file: for line in file: org = line.rstrip('\n').lower() add_org_group(org, iam_connection) else: parser.print_usage() sys.exit(1) sys.exit(0)
group_name = "edx-course-data-{org}".format(org=org) try: iam_connection.create_group(GroupName=group_name) except ClientError as bse: if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else: print(bse) try: iam_connection.put_group_policy( GroupName=group_name, PolicyName=group_name, PolicyDocument=template.substitute(org=org) ) except boto.exception.BotoServerError as bse: if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else: print(bse) print(template.substitute(org=org))
identifier_body
create_org_data_czar_policy.py
""" create_org_data_czar_policy.py Creates an IAM group for an edX org and applies an S3 policy to that group that allows for read-only access to the group. """ import argparse import boto3 from botocore.exceptions import ClientError from string import Template import sys template = Template("""{ "Version":"2012-10-17", "Statement": [ { "Sid": "AllowListingOfOrgFolder", "Action": ["s3:ListBucket"], "Effect": "Allow", "Resource": ["arn:aws:s3:::edx-course-data"], "Condition":{"StringLike":{"s3:prefix":["$org","$org/*"]}} }, { "Sid": "AllowGetBucketLocation", "Action": ["s3:GetBucketLocation"], "Effect": "Allow", "Resource": ["arn:aws:s3:::edx-course-data"] }, { "Sid": "AllowGetS3ActionInOrgFolder", "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::edx-course-data/$org/*"] } ] }""") def add_org_group(org, iam_connection): group_name = "edx-course-data-{org}".format(org=org) try:
if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else: print(bse) try: iam_connection.put_group_policy( GroupName=group_name, PolicyName=group_name, PolicyDocument=template.substitute(org=org) ) except boto.exception.BotoServerError as bse: if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else: print(bse) print(template.substitute(org=org)) parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-o', '--org', help='Name of the org for which to create an IAM ' 'role and policy, this should have the same ' 'name as the S3 bucket') group.add_argument('-f', '--file', help='The path to a file containing one org name ' 'per line.') args = parser.parse_args() iam_connection = boto3.client('iam') if args.org: add_org_group(args.org.rstrip('\n').lower(), iam_connection) elif args.file: with open(args.file) as file: for line in file: org = line.rstrip('\n').lower() add_org_group(org, iam_connection) else: parser.print_usage() sys.exit(1) sys.exit(0)
iam_connection.create_group(GroupName=group_name) except ClientError as bse:
random_line_split
advent9.rs
// advent9.rs // // Traveling Santa Problem extern crate permutohedron; #[macro_use] extern crate scan_fmt; use std::io; fn main() { let mut city_table = CityDistances::new(); loop { let mut input = String::new(); let result = io::stdin().read_line(&mut input); match result { Ok(byte_count) => if byte_count == 0 { break; }, Err(_) => { println!("error reading from stdin"); break; } } // Parse input let (city1, city2, distance) = scan_fmt!(&input, "{} to {} = {}", String, String, u32); city_table.add_distance(&city1.unwrap(), &city2.unwrap(), distance.unwrap()); } let min = calc_shortest_distance(&city_table); println!("Shortest route: {}", min); let max = calc_longest_distance(&city_table); println!("Longest route: {}", max); } struct CityDistances { cities: Vec<String>, distance_map: std::collections::HashMap<(usize, usize), u32>, } impl CityDistances { fn new() -> CityDistances { CityDistances{cities: Vec::new(), distance_map: std::collections::HashMap::new()} } fn
(&mut self, city: &str) -> usize { match self.cities.iter().position(|x| x == city) { Some(idx) => idx, None => { self.cities.push(String::from(city)); self.cities.len() - 1 } } } fn add_distance(&mut self, city1: &str, city2: &str, distance: u32) { let idx1 = self.find_city_idx(city1); let idx2 = self.find_city_idx(city2); // insert both possible tuples; we won't run out of memory and it makes things simpler self.distance_map.insert((idx1, idx2), distance); self.distance_map.insert((idx2, idx1), distance); } fn find_distance(&self, idx1: usize, idx2: usize) -> u32 { *self.distance_map.get(&(idx1, idx2)).unwrap() } } fn calc_shortest_distance(city_table: &CityDistances) -> u32 { let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .min().unwrap() } #[test] fn test_distance_struct() { let mut cities = CityDistances::new(); cities.add_distance("Hoth", "Tatooine", 1000); cities.add_distance("Hoth", "Coruscant", 300); cities.add_distance("Coruscant", "Tatooine", 900); assert_eq!(1000, cities.find_distance(0, 1)); assert_eq!(1000, cities.find_distance(1, 0)); assert_eq!(300, cities.find_distance(0, 2)); assert_eq!(300, cities.find_distance(2, 0)); assert_eq!(900, cities.find_distance(1, 2)); assert_eq!(900, cities.find_distance(2, 1)); } #[test] fn test_calc_shortest_distance() { let mut cities = CityDistances::new(); cities.add_distance("London", "Dublin", 464); cities.add_distance("London", "Belfast", 518); cities.add_distance("Dublin", "Belfast", 141); assert_eq!(605, calc_shortest_distance(&cities)); } // Part 2 fn calc_longest_distance(city_table: &CityDistances) -> u32 { let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .max().unwrap() }
find_city_idx
identifier_name
advent9.rs
// advent9.rs // // Traveling Santa Problem extern crate permutohedron; #[macro_use] extern crate scan_fmt; use std::io; fn main() { let mut city_table = CityDistances::new(); loop { let mut input = String::new(); let result = io::stdin().read_line(&mut input); match result { Ok(byte_count) => if byte_count == 0 { break; }, Err(_) => { println!("error reading from stdin"); break; } } // Parse input let (city1, city2, distance) = scan_fmt!(&input, "{} to {} = {}", String, String, u32); city_table.add_distance(&city1.unwrap(), &city2.unwrap(), distance.unwrap()); } let min = calc_shortest_distance(&city_table); println!("Shortest route: {}", min); let max = calc_longest_distance(&city_table); println!("Longest route: {}", max); } struct CityDistances { cities: Vec<String>, distance_map: std::collections::HashMap<(usize, usize), u32>, } impl CityDistances { fn new() -> CityDistances { CityDistances{cities: Vec::new(), distance_map: std::collections::HashMap::new()} } fn find_city_idx(&mut self, city: &str) -> usize { match self.cities.iter().position(|x| x == city) { Some(idx) => idx, None => { self.cities.push(String::from(city)); self.cities.len() - 1 } } } fn add_distance(&mut self, city1: &str, city2: &str, distance: u32) { let idx1 = self.find_city_idx(city1); let idx2 = self.find_city_idx(city2); // insert both possible tuples; we won't run out of memory and it makes things simpler self.distance_map.insert((idx1, idx2), distance); self.distance_map.insert((idx2, idx1), distance); } fn find_distance(&self, idx1: usize, idx2: usize) -> u32 { *self.distance_map.get(&(idx1, idx2)).unwrap() } } fn calc_shortest_distance(city_table: &CityDistances) -> u32
#[test] fn test_distance_struct() { let mut cities = CityDistances::new(); cities.add_distance("Hoth", "Tatooine", 1000); cities.add_distance("Hoth", "Coruscant", 300); cities.add_distance("Coruscant", "Tatooine", 900); assert_eq!(1000, cities.find_distance(0, 1)); assert_eq!(1000, cities.find_distance(1, 0)); assert_eq!(300, cities.find_distance(0, 2)); assert_eq!(300, cities.find_distance(2, 0)); assert_eq!(900, cities.find_distance(1, 2)); assert_eq!(900, cities.find_distance(2, 1)); } #[test] fn test_calc_shortest_distance() { let mut cities = CityDistances::new(); cities.add_distance("London", "Dublin", 464); cities.add_distance("London", "Belfast", 518); cities.add_distance("Dublin", "Belfast", 141); assert_eq!(605, calc_shortest_distance(&cities)); } // Part 2 fn calc_longest_distance(city_table: &CityDistances) -> u32 { let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .max().unwrap() }
{ let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .min().unwrap() }
identifier_body
advent9.rs
// advent9.rs // // Traveling Santa Problem extern crate permutohedron; #[macro_use] extern crate scan_fmt; use std::io; fn main() { let mut city_table = CityDistances::new(); loop {
match result { Ok(byte_count) => if byte_count == 0 { break; }, Err(_) => { println!("error reading from stdin"); break; } } // Parse input let (city1, city2, distance) = scan_fmt!(&input, "{} to {} = {}", String, String, u32); city_table.add_distance(&city1.unwrap(), &city2.unwrap(), distance.unwrap()); } let min = calc_shortest_distance(&city_table); println!("Shortest route: {}", min); let max = calc_longest_distance(&city_table); println!("Longest route: {}", max); } struct CityDistances { cities: Vec<String>, distance_map: std::collections::HashMap<(usize, usize), u32>, } impl CityDistances { fn new() -> CityDistances { CityDistances{cities: Vec::new(), distance_map: std::collections::HashMap::new()} } fn find_city_idx(&mut self, city: &str) -> usize { match self.cities.iter().position(|x| x == city) { Some(idx) => idx, None => { self.cities.push(String::from(city)); self.cities.len() - 1 } } } fn add_distance(&mut self, city1: &str, city2: &str, distance: u32) { let idx1 = self.find_city_idx(city1); let idx2 = self.find_city_idx(city2); // insert both possible tuples; we won't run out of memory and it makes things simpler self.distance_map.insert((idx1, idx2), distance); self.distance_map.insert((idx2, idx1), distance); } fn find_distance(&self, idx1: usize, idx2: usize) -> u32 { *self.distance_map.get(&(idx1, idx2)).unwrap() } } fn calc_shortest_distance(city_table: &CityDistances) -> u32 { let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .min().unwrap() } #[test] fn test_distance_struct() { let mut cities = CityDistances::new(); cities.add_distance("Hoth", "Tatooine", 1000); cities.add_distance("Hoth", "Coruscant", 300); cities.add_distance("Coruscant", "Tatooine", 900); assert_eq!(1000, cities.find_distance(0, 1)); assert_eq!(1000, cities.find_distance(1, 0)); assert_eq!(300, cities.find_distance(0, 2)); assert_eq!(300, cities.find_distance(2, 0)); assert_eq!(900, cities.find_distance(1, 2)); assert_eq!(900, cities.find_distance(2, 1)); } #[test] fn test_calc_shortest_distance() { let mut cities = CityDistances::new(); cities.add_distance("London", "Dublin", 464); cities.add_distance("London", "Belfast", 518); cities.add_distance("Dublin", "Belfast", 141); assert_eq!(605, calc_shortest_distance(&cities)); } // Part 2 fn calc_longest_distance(city_table: &CityDistances) -> u32 { let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .max().unwrap() }
let mut input = String::new(); let result = io::stdin().read_line(&mut input);
random_line_split
test-fsreqwrap-readFile.js
'use strict'; const common = require('../common'); const assert = require('assert'); const tick = require('./tick'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const fs = require('fs'); const hooks = initHooks(); hooks.enable(); fs.readFile(__filename, common.mustCall(onread)); function onread() { const as = hooks.activitiesOfTypes('FSREQWRAP'); let lastParent = 1; for (let i = 0; i < as.length; i++) { const a = as[i]; assert.strictEqual(a.type, 'FSREQWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, lastParent); lastParent = a.uid; } checkInvocations(as[0], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[0]: while in onread callback');
checkInvocations(as[1], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[1]: while in onread callback'); checkInvocations(as[2], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[2]: while in onread callback'); // this callback is called from within the last fs req callback therefore // the last req is still going and after/destroy haven't been called yet checkInvocations(as[3], { init: 1, before: 1 }, 'reqwrap[3]: while in onread callback'); tick(2); } process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('FSREQWRAP'); const as = hooks.activitiesOfTypes('FSREQWRAP'); const a = as.pop(); checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, 'when process exits'); }
random_line_split
test-fsreqwrap-readFile.js
'use strict'; const common = require('../common'); const assert = require('assert'); const tick = require('./tick'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const fs = require('fs'); const hooks = initHooks(); hooks.enable(); fs.readFile(__filename, common.mustCall(onread)); function
() { const as = hooks.activitiesOfTypes('FSREQWRAP'); let lastParent = 1; for (let i = 0; i < as.length; i++) { const a = as[i]; assert.strictEqual(a.type, 'FSREQWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, lastParent); lastParent = a.uid; } checkInvocations(as[0], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[0]: while in onread callback'); checkInvocations(as[1], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[1]: while in onread callback'); checkInvocations(as[2], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[2]: while in onread callback'); // this callback is called from within the last fs req callback therefore // the last req is still going and after/destroy haven't been called yet checkInvocations(as[3], { init: 1, before: 1 }, 'reqwrap[3]: while in onread callback'); tick(2); } process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('FSREQWRAP'); const as = hooks.activitiesOfTypes('FSREQWRAP'); const a = as.pop(); checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, 'when process exits'); }
onread
identifier_name
test-fsreqwrap-readFile.js
'use strict'; const common = require('../common'); const assert = require('assert'); const tick = require('./tick'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const fs = require('fs'); const hooks = initHooks(); hooks.enable(); fs.readFile(__filename, common.mustCall(onread)); function onread()
process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('FSREQWRAP'); const as = hooks.activitiesOfTypes('FSREQWRAP'); const a = as.pop(); checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, 'when process exits'); }
{ const as = hooks.activitiesOfTypes('FSREQWRAP'); let lastParent = 1; for (let i = 0; i < as.length; i++) { const a = as[i]; assert.strictEqual(a.type, 'FSREQWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, lastParent); lastParent = a.uid; } checkInvocations(as[0], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[0]: while in onread callback'); checkInvocations(as[1], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[1]: while in onread callback'); checkInvocations(as[2], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[2]: while in onread callback'); // this callback is called from within the last fs req callback therefore // the last req is still going and after/destroy haven't been called yet checkInvocations(as[3], { init: 1, before: 1 }, 'reqwrap[3]: while in onread callback'); tick(2); }
identifier_body
test-fsreqwrap-readFile.js
'use strict'; const common = require('../common'); const assert = require('assert'); const tick = require('./tick'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const fs = require('fs'); const hooks = initHooks(); hooks.enable(); fs.readFile(__filename, common.mustCall(onread)); function onread() { const as = hooks.activitiesOfTypes('FSREQWRAP'); let lastParent = 1; for (let i = 0; i < as.length; i++)
checkInvocations(as[0], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[0]: while in onread callback'); checkInvocations(as[1], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[1]: while in onread callback'); checkInvocations(as[2], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[2]: while in onread callback'); // this callback is called from within the last fs req callback therefore // the last req is still going and after/destroy haven't been called yet checkInvocations(as[3], { init: 1, before: 1 }, 'reqwrap[3]: while in onread callback'); tick(2); } process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('FSREQWRAP'); const as = hooks.activitiesOfTypes('FSREQWRAP'); const a = as.pop(); checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, 'when process exits'); }
{ const a = as[i]; assert.strictEqual(a.type, 'FSREQWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, lastParent); lastParent = a.uid; }
conditional_block
jsonconfig.py
""" Read a dictionary from a JSON file, and add its contents to a Python dictionary. """ import json import types from instmakelib import rtimport INSTMAKE_SITE_DIR = "instmakesite" # These are the supported field names # =================================== # The name of the plugin (without ".py") for logging # usage of instmake CONFIG_USAGE_LOGGER = "usage-logger" # The name of the plugin (without ".py") for normalizing # path names in the clidiff report. CONFIG_CLIDIFF_NORMPATH = "clidiff-normpath" def update(caller_config, json_filename): # This will throw errors fh = open(json_filename) file_config = json.load(fh) fh.close() assert type(file_config) == types.DictType caller_config.update(file_config) def
(name): """Import a plugin from the instmakesite directory. The import can throw exceptions that the caller has to catch.""" plugin_name = INSTMAKE_SITE_DIR + "." + name return rtimport.rtimport(plugin_name)
load_site_plugin
identifier_name
jsonconfig.py
and add its contents to a Python dictionary. """ import json import types from instmakelib import rtimport INSTMAKE_SITE_DIR = "instmakesite" # These are the supported field names # =================================== # The name of the plugin (without ".py") for logging # usage of instmake CONFIG_USAGE_LOGGER = "usage-logger" # The name of the plugin (without ".py") for normalizing # path names in the clidiff report. CONFIG_CLIDIFF_NORMPATH = "clidiff-normpath" def update(caller_config, json_filename): # This will throw errors fh = open(json_filename) file_config = json.load(fh) fh.close() assert type(file_config) == types.DictType caller_config.update(file_config) def load_site_plugin(name): """Import a plugin from the instmakesite directory. The import can throw exceptions that the caller has to catch.""" plugin_name = INSTMAKE_SITE_DIR + "." + name return rtimport.rtimport(plugin_name)
""" Read a dictionary from a JSON file,
random_line_split
jsonconfig.py
""" Read a dictionary from a JSON file, and add its contents to a Python dictionary. """ import json import types from instmakelib import rtimport INSTMAKE_SITE_DIR = "instmakesite" # These are the supported field names # =================================== # The name of the plugin (without ".py") for logging # usage of instmake CONFIG_USAGE_LOGGER = "usage-logger" # The name of the plugin (without ".py") for normalizing # path names in the clidiff report. CONFIG_CLIDIFF_NORMPATH = "clidiff-normpath" def update(caller_config, json_filename): # This will throw errors fh = open(json_filename) file_config = json.load(fh) fh.close() assert type(file_config) == types.DictType caller_config.update(file_config) def load_site_plugin(name):
"""Import a plugin from the instmakesite directory. The import can throw exceptions that the caller has to catch.""" plugin_name = INSTMAKE_SITE_DIR + "." + name return rtimport.rtimport(plugin_name)
identifier_body
Teacher-Quiz.py
# Teacher Quiz - Python Code - Elizabeth Tweedale import csv, random def askName(): # askName function returns the name of the student print("Welcome to the Super Python Quiz!") yourName = input("What is your name? ") print ("Hello",str(yourName)) return yourName def getQuestions(): # getQuestions reads in the questions from a CSV file questions = [] # this creates an empty list for adding the questions to with open("SuperPythonQuiz.csv", mode="r", encoding="utf-8") as myFile: myQuiz = csv.reader(myFile) for row in myQuiz: questions.append(row) return questions def
(question,score): # askQuestion prints the question and choices to the screen then checks the answer print(question[0]) # print the question - this is in the [0] position of the row for eachChoice in question[1:-1]: # print each choice from [1] to the last position [-1] print("{0:>5}{1}".format("", eachChoice)) answer = input("Please select an answer: ") # get the student's answer if answer == question[-1]: # check if the answer matches the last position in the question, the correct answer print("Correct!") # if it's correct, tell the user and add one to the score score += 1 else: # if it's incorrect, tell the user what the correct answer was print("Incorrect, the correct answer was {0}.".format(question[-1])) return score # return the score def recordScore(studentName, score): with open("QuizResults.txt", mode="a+",encoding="utf-8") as myFile: # note the '+' sign after the a means if the file does not exist, then create it myFile.write(str(studentName) + "," + str(score) + "\n") # write name,score to the file # "\n" will add a new line to the file so that it's ready for the next name def main(): studentName = askName() # call the askName function questions = getQuestions() # call the getQuestions function score = 0 # initialise the score to 0 number = len(questions) # use the number to keep track of the total number of questions - which is the length of the 'questions' list for eachQuestion in range(number): # reppeat for each question question = random.choice(questions) # choose a random question from the questions list score = askQuestion(question,score) # ask the question and update the score questions.remove(question) # remove the current question from the list so that you don't ask it again print("Your final score is:", score, "out of:", number) # tell the user what their final score is recordScore(studentName, score) # call the recordScore function main()
askQuestion
identifier_name
Teacher-Quiz.py
# Teacher Quiz - Python Code - Elizabeth Tweedale import csv, random def askName(): # askName function returns the name of the student print("Welcome to the Super Python Quiz!") yourName = input("What is your name? ") print ("Hello",str(yourName)) return yourName def getQuestions(): # getQuestions reads in the questions from a CSV file
def askQuestion(question,score): # askQuestion prints the question and choices to the screen then checks the answer print(question[0]) # print the question - this is in the [0] position of the row for eachChoice in question[1:-1]: # print each choice from [1] to the last position [-1] print("{0:>5}{1}".format("", eachChoice)) answer = input("Please select an answer: ") # get the student's answer if answer == question[-1]: # check if the answer matches the last position in the question, the correct answer print("Correct!") # if it's correct, tell the user and add one to the score score += 1 else: # if it's incorrect, tell the user what the correct answer was print("Incorrect, the correct answer was {0}.".format(question[-1])) return score # return the score def recordScore(studentName, score): with open("QuizResults.txt", mode="a+",encoding="utf-8") as myFile: # note the '+' sign after the a means if the file does not exist, then create it myFile.write(str(studentName) + "," + str(score) + "\n") # write name,score to the file # "\n" will add a new line to the file so that it's ready for the next name def main(): studentName = askName() # call the askName function questions = getQuestions() # call the getQuestions function score = 0 # initialise the score to 0 number = len(questions) # use the number to keep track of the total number of questions - which is the length of the 'questions' list for eachQuestion in range(number): # reppeat for each question question = random.choice(questions) # choose a random question from the questions list score = askQuestion(question,score) # ask the question and update the score questions.remove(question) # remove the current question from the list so that you don't ask it again print("Your final score is:", score, "out of:", number) # tell the user what their final score is recordScore(studentName, score) # call the recordScore function main()
questions = [] # this creates an empty list for adding the questions to with open("SuperPythonQuiz.csv", mode="r", encoding="utf-8") as myFile: myQuiz = csv.reader(myFile) for row in myQuiz: questions.append(row) return questions
identifier_body
Teacher-Quiz.py
# Teacher Quiz - Python Code - Elizabeth Tweedale import csv, random def askName(): # askName function returns the name of the student print("Welcome to the Super Python Quiz!") yourName = input("What is your name? ") print ("Hello",str(yourName)) return yourName def getQuestions(): # getQuestions reads in the questions from a CSV file questions = [] # this creates an empty list for adding the questions to with open("SuperPythonQuiz.csv", mode="r", encoding="utf-8") as myFile: myQuiz = csv.reader(myFile) for row in myQuiz: questions.append(row) return questions def askQuestion(question,score): # askQuestion prints the question and choices to the screen then checks the answer print(question[0]) # print the question - this is in the [0] position of the row for eachChoice in question[1:-1]: # print each choice from [1] to the last position [-1] print("{0:>5}{1}".format("", eachChoice)) answer = input("Please select an answer: ") # get the student's answer if answer == question[-1]: # check if the answer matches the last position in the question, the correct answer print("Correct!") # if it's correct, tell the user and add one to the score score += 1 else: # if it's incorrect, tell the user what the correct answer was
return score # return the score def recordScore(studentName, score): with open("QuizResults.txt", mode="a+",encoding="utf-8") as myFile: # note the '+' sign after the a means if the file does not exist, then create it myFile.write(str(studentName) + "," + str(score) + "\n") # write name,score to the file # "\n" will add a new line to the file so that it's ready for the next name def main(): studentName = askName() # call the askName function questions = getQuestions() # call the getQuestions function score = 0 # initialise the score to 0 number = len(questions) # use the number to keep track of the total number of questions - which is the length of the 'questions' list for eachQuestion in range(number): # reppeat for each question question = random.choice(questions) # choose a random question from the questions list score = askQuestion(question,score) # ask the question and update the score questions.remove(question) # remove the current question from the list so that you don't ask it again print("Your final score is:", score, "out of:", number) # tell the user what their final score is recordScore(studentName, score) # call the recordScore function main()
print("Incorrect, the correct answer was {0}.".format(question[-1]))
conditional_block
Teacher-Quiz.py
# Teacher Quiz - Python Code - Elizabeth Tweedale import csv, random def askName(): # askName function returns the name of the student print("Welcome to the Super Python Quiz!") yourName = input("What is your name? ") print ("Hello",str(yourName)) return yourName def getQuestions(): # getQuestions reads in the questions from a CSV file questions = [] # this creates an empty list for adding the questions to with open("SuperPythonQuiz.csv", mode="r", encoding="utf-8") as myFile: myQuiz = csv.reader(myFile) for row in myQuiz: questions.append(row) return questions def askQuestion(question,score): # askQuestion prints the question and choices to the screen then checks the answer print(question[0]) # print the question - this is in the [0] position of the row for eachChoice in question[1:-1]: # print each choice from [1] to the last position [-1] print("{0:>5}{1}".format("", eachChoice)) answer = input("Please select an answer: ") # get the student's answer if answer == question[-1]: # check if the answer matches the last position in the question, the correct answer print("Correct!") # if it's correct, tell the user and add one to the score score += 1 else: # if it's incorrect, tell the user what the correct answer was print("Incorrect, the correct answer was {0}.".format(question[-1])) return score # return the score def recordScore(studentName, score): with open("QuizResults.txt", mode="a+",encoding="utf-8") as myFile: # note the '+' sign after the a means if the file does not exist, then create it myFile.write(str(studentName) + "," + str(score) + "\n") # write name,score to the file # "\n" will add a new line to the file so that it's ready for the next name def main(): studentName = askName() # call the askName function questions = getQuestions() # call the getQuestions function score = 0 # initialise the score to 0
number = len(questions) # use the number to keep track of the total number of questions - which is the length of the 'questions' list for eachQuestion in range(number): # reppeat for each question question = random.choice(questions) # choose a random question from the questions list score = askQuestion(question,score) # ask the question and update the score questions.remove(question) # remove the current question from the list so that you don't ask it again print("Your final score is:", score, "out of:", number) # tell the user what their final score is recordScore(studentName, score) # call the recordScore function main()
random_line_split
RepositoryList.js
import React from 'react' import { filter, get } from 'lodash' import utils from '~/utils' import Filter from '~/components/filter/Filter' import InfiniteScroll from '~/components/infinite-scroll/InfiniteScroll' import RepositoryCard from '~/components/repository-list/repository-card/RepositoryCard' /** * The RepositoryList object class. */ class RepositoryList extends React.Component { // Initial state. state = { repos: this.props.repos, filteredRepos: this.props.repos, } // Default props. static defaultProps = { repos: [], } /** * Update the internal state when this component receive new repos prop. * @param {Object} nextProps */ componentWillReceiveProps(nextProps) { const currRepos = get(this.props, 'repos', []) const nextRepos = get(nextProps, 'repos', []) if (currRepos.length !== nextRepos.length) { this.setState({ repos: nextRepos, filteredRepos: nextRepos, }) } } /** * Render this component. */ render() { const { filteredRepos } = this.state return ( <div> <Filter placeholder="Filter repositories by name or author..." onChange={ (value) => this.filterChanged(value) } /> <InfiniteScroll items={ filteredRepos }
/> ) } /> </div> ) } /** * Handle filter value changes. * @param {String} value The new filter value. */ filterChanged(value) { const { repos } = this.state // Filter repos. const query = utils.unicodeNormalize(value) const matcher = new RegExp(utils.escapeRegExp(query), 'i') const filteredRepos = filter(repos, (repo) => { return matcher.test(repo.normalizedName) || matcher.test(repo.normalizedDescription) || matcher.test(repo.user.normalizedName) }) // Update the state. this.setState((state) => ({ filteredRepos, })) } } export default RepositoryList
render={ (repo) => ( <RepositoryCard key={ repo.id } repo={ repo }
random_line_split
RepositoryList.js
import React from 'react' import { filter, get } from 'lodash' import utils from '~/utils' import Filter from '~/components/filter/Filter' import InfiniteScroll from '~/components/infinite-scroll/InfiniteScroll' import RepositoryCard from '~/components/repository-list/repository-card/RepositoryCard' /** * The RepositoryList object class. */ class RepositoryList extends React.Component { // Initial state. state = { repos: this.props.repos, filteredRepos: this.props.repos, } // Default props. static defaultProps = { repos: [], } /** * Update the internal state when this component receive new repos prop. * @param {Object} nextProps */ componentWillReceiveProps(nextProps) { const currRepos = get(this.props, 'repos', []) const nextRepos = get(nextProps, 'repos', []) if (currRepos.length !== nextRepos.length) { this.setState({ repos: nextRepos, filteredRepos: nextRepos, }) } } /** * Render this component. */
() { const { filteredRepos } = this.state return ( <div> <Filter placeholder="Filter repositories by name or author..." onChange={ (value) => this.filterChanged(value) } /> <InfiniteScroll items={ filteredRepos } render={ (repo) => ( <RepositoryCard key={ repo.id } repo={ repo } /> ) } /> </div> ) } /** * Handle filter value changes. * @param {String} value The new filter value. */ filterChanged(value) { const { repos } = this.state // Filter repos. const query = utils.unicodeNormalize(value) const matcher = new RegExp(utils.escapeRegExp(query), 'i') const filteredRepos = filter(repos, (repo) => { return matcher.test(repo.normalizedName) || matcher.test(repo.normalizedDescription) || matcher.test(repo.user.normalizedName) }) // Update the state. this.setState((state) => ({ filteredRepos, })) } } export default RepositoryList
render
identifier_name
RepositoryList.js
import React from 'react' import { filter, get } from 'lodash' import utils from '~/utils' import Filter from '~/components/filter/Filter' import InfiniteScroll from '~/components/infinite-scroll/InfiniteScroll' import RepositoryCard from '~/components/repository-list/repository-card/RepositoryCard' /** * The RepositoryList object class. */ class RepositoryList extends React.Component { // Initial state. state = { repos: this.props.repos, filteredRepos: this.props.repos, } // Default props. static defaultProps = { repos: [], } /** * Update the internal state when this component receive new repos prop. * @param {Object} nextProps */ componentWillReceiveProps(nextProps) { const currRepos = get(this.props, 'repos', []) const nextRepos = get(nextProps, 'repos', []) if (currRepos.length !== nextRepos.length)
} /** * Render this component. */ render() { const { filteredRepos } = this.state return ( <div> <Filter placeholder="Filter repositories by name or author..." onChange={ (value) => this.filterChanged(value) } /> <InfiniteScroll items={ filteredRepos } render={ (repo) => ( <RepositoryCard key={ repo.id } repo={ repo } /> ) } /> </div> ) } /** * Handle filter value changes. * @param {String} value The new filter value. */ filterChanged(value) { const { repos } = this.state // Filter repos. const query = utils.unicodeNormalize(value) const matcher = new RegExp(utils.escapeRegExp(query), 'i') const filteredRepos = filter(repos, (repo) => { return matcher.test(repo.normalizedName) || matcher.test(repo.normalizedDescription) || matcher.test(repo.user.normalizedName) }) // Update the state. this.setState((state) => ({ filteredRepos, })) } } export default RepositoryList
{ this.setState({ repos: nextRepos, filteredRepos: nextRepos, }) }
conditional_block
RepositoryList.js
import React from 'react' import { filter, get } from 'lodash' import utils from '~/utils' import Filter from '~/components/filter/Filter' import InfiniteScroll from '~/components/infinite-scroll/InfiniteScroll' import RepositoryCard from '~/components/repository-list/repository-card/RepositoryCard' /** * The RepositoryList object class. */ class RepositoryList extends React.Component { // Initial state. state = { repos: this.props.repos, filteredRepos: this.props.repos, } // Default props. static defaultProps = { repos: [], } /** * Update the internal state when this component receive new repos prop. * @param {Object} nextProps */ componentWillReceiveProps(nextProps)
/** * Render this component. */ render() { const { filteredRepos } = this.state return ( <div> <Filter placeholder="Filter repositories by name or author..." onChange={ (value) => this.filterChanged(value) } /> <InfiniteScroll items={ filteredRepos } render={ (repo) => ( <RepositoryCard key={ repo.id } repo={ repo } /> ) } /> </div> ) } /** * Handle filter value changes. * @param {String} value The new filter value. */ filterChanged(value) { const { repos } = this.state // Filter repos. const query = utils.unicodeNormalize(value) const matcher = new RegExp(utils.escapeRegExp(query), 'i') const filteredRepos = filter(repos, (repo) => { return matcher.test(repo.normalizedName) || matcher.test(repo.normalizedDescription) || matcher.test(repo.user.normalizedName) }) // Update the state. this.setState((state) => ({ filteredRepos, })) } } export default RepositoryList
{ const currRepos = get(this.props, 'repos', []) const nextRepos = get(nextProps, 'repos', []) if (currRepos.length !== nextRepos.length) { this.setState({ repos: nextRepos, filteredRepos: nextRepos, }) } }
identifier_body
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use cell::UnsafeCell; use mem; use sync::atomic::{AtomicU32, Ordering}; use sys::cloudabi::abi; use sys::rwlock::{self, RWLock}; extern "C" { #[thread_local] static __pthread_thread_id: abi::tid; } // Implement Mutex using an RWLock. This doesn't introduce any // performance overhead in this environment, as the operations would be // implemented identically. pub struct Mutex(RWLock); pub unsafe fn raw(m: &Mutex) -> *mut AtomicU32 { rwlock::raw(&m.0) } impl Mutex { pub const fn new() -> Mutex { Mutex(RWLock::new()) } pub unsafe fn init(&mut self) { // This function should normally reinitialize the mutex after // moving it to a different memory address. This implementation // does not require adjustments after moving. } pub unsafe fn try_lock(&self) -> bool { self.0.try_write() } pub unsafe fn lock(&self) { self.0.write() } pub unsafe fn unlock(&self) { self.0.write_unlock() } pub unsafe fn destroy(&self) { self.0.destroy() } } pub struct ReentrantMutex { lock: UnsafeCell<AtomicU32>, recursion: UnsafeCell<u32>, } impl ReentrantMutex { pub unsafe fn uninitialized() -> ReentrantMutex { mem::uninitialized() } pub unsafe fn init(&mut self) { self.lock = UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)); self.recursion = UnsafeCell::new(0); } pub unsafe fn try_lock(&self) -> bool { // Attempt to acquire the lock. let lock = self.lock.get(); let recursion = self.recursion.get(); if let Err(old) = (*lock).compare_exchange( abi::LOCK_UNLOCKED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, Ordering::Acquire, Ordering::Relaxed, ) { // If we fail to acquire the lock, it may be the case // that we've already acquired it and may need to recurse. if old & !abi::LOCK_KERNEL_MANAGED.0 == __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0 { *recursion += 1; true } else { false } } else { // Success. assert_eq!(*recursion, 0, "Mutex has invalid recursion count"); true } } pub unsafe fn lock(&self) { if !self.try_lock() { // Call into the kernel to acquire a write lock. let lock = self.lock.get(); let subscription = abi::subscription { type_: abi::eventtype::LOCK_WRLOCK, union: abi::subscription_union { lock: abi::subscription_lock { lock: lock as *mut abi::lock, lock_scope: abi::scope::PRIVATE, }, }, ..mem::zeroed() }; let mut event: abi::event = mem::uninitialized(); let mut nevents: usize = mem::uninitialized(); let ret = abi::poll(&subscription, &mut event, 1, &mut nevents); assert_eq!(ret, abi::errno::SUCCESS, "Failed to acquire mutex"); assert_eq!(event.error, abi::errno::SUCCESS, "Failed to acquire mutex"); } } pub unsafe fn unlock(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed) & !abi::LOCK_KERNEL_MANAGED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, "This mutex is locked by a different thread" ); if *recursion > 0 { *recursion -= 1; } else if !(*lock) .compare_exchange( __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, abi::LOCK_UNLOCKED.0, Ordering::Release, Ordering::Relaxed, ) .is_ok()
} pub unsafe fn destroy(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed), abi::LOCK_UNLOCKED.0, "Attempted to destroy locked mutex" ); assert_eq!(*recursion, 0, "Recursion counter invalid"); } }
{ // Lock is managed by kernelspace. Call into the kernel // to unblock waiting threads. let ret = abi::lock_unlock(lock as *mut abi::lock, abi::scope::PRIVATE); assert_eq!(ret, abi::errno::SUCCESS, "Failed to unlock a mutex"); }
conditional_block
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use cell::UnsafeCell; use mem; use sync::atomic::{AtomicU32, Ordering}; use sys::cloudabi::abi; use sys::rwlock::{self, RWLock}; extern "C" { #[thread_local] static __pthread_thread_id: abi::tid; } // Implement Mutex using an RWLock. This doesn't introduce any // performance overhead in this environment, as the operations would be // implemented identically. pub struct Mutex(RWLock); pub unsafe fn raw(m: &Mutex) -> *mut AtomicU32 { rwlock::raw(&m.0) } impl Mutex { pub const fn new() -> Mutex { Mutex(RWLock::new()) } pub unsafe fn init(&mut self) { // This function should normally reinitialize the mutex after // moving it to a different memory address. This implementation // does not require adjustments after moving. } pub unsafe fn try_lock(&self) -> bool { self.0.try_write() } pub unsafe fn lock(&self) { self.0.write() } pub unsafe fn unlock(&self) { self.0.write_unlock() } pub unsafe fn destroy(&self) { self.0.destroy() } } pub struct ReentrantMutex { lock: UnsafeCell<AtomicU32>, recursion: UnsafeCell<u32>, }
pub unsafe fn uninitialized() -> ReentrantMutex { mem::uninitialized() } pub unsafe fn init(&mut self) { self.lock = UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)); self.recursion = UnsafeCell::new(0); } pub unsafe fn try_lock(&self) -> bool { // Attempt to acquire the lock. let lock = self.lock.get(); let recursion = self.recursion.get(); if let Err(old) = (*lock).compare_exchange( abi::LOCK_UNLOCKED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, Ordering::Acquire, Ordering::Relaxed, ) { // If we fail to acquire the lock, it may be the case // that we've already acquired it and may need to recurse. if old & !abi::LOCK_KERNEL_MANAGED.0 == __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0 { *recursion += 1; true } else { false } } else { // Success. assert_eq!(*recursion, 0, "Mutex has invalid recursion count"); true } } pub unsafe fn lock(&self) { if !self.try_lock() { // Call into the kernel to acquire a write lock. let lock = self.lock.get(); let subscription = abi::subscription { type_: abi::eventtype::LOCK_WRLOCK, union: abi::subscription_union { lock: abi::subscription_lock { lock: lock as *mut abi::lock, lock_scope: abi::scope::PRIVATE, }, }, ..mem::zeroed() }; let mut event: abi::event = mem::uninitialized(); let mut nevents: usize = mem::uninitialized(); let ret = abi::poll(&subscription, &mut event, 1, &mut nevents); assert_eq!(ret, abi::errno::SUCCESS, "Failed to acquire mutex"); assert_eq!(event.error, abi::errno::SUCCESS, "Failed to acquire mutex"); } } pub unsafe fn unlock(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed) & !abi::LOCK_KERNEL_MANAGED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, "This mutex is locked by a different thread" ); if *recursion > 0 { *recursion -= 1; } else if !(*lock) .compare_exchange( __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, abi::LOCK_UNLOCKED.0, Ordering::Release, Ordering::Relaxed, ) .is_ok() { // Lock is managed by kernelspace. Call into the kernel // to unblock waiting threads. let ret = abi::lock_unlock(lock as *mut abi::lock, abi::scope::PRIVATE); assert_eq!(ret, abi::errno::SUCCESS, "Failed to unlock a mutex"); } } pub unsafe fn destroy(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed), abi::LOCK_UNLOCKED.0, "Attempted to destroy locked mutex" ); assert_eq!(*recursion, 0, "Recursion counter invalid"); } }
impl ReentrantMutex {
random_line_split
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use cell::UnsafeCell; use mem; use sync::atomic::{AtomicU32, Ordering}; use sys::cloudabi::abi; use sys::rwlock::{self, RWLock}; extern "C" { #[thread_local] static __pthread_thread_id: abi::tid; } // Implement Mutex using an RWLock. This doesn't introduce any // performance overhead in this environment, as the operations would be // implemented identically. pub struct Mutex(RWLock); pub unsafe fn raw(m: &Mutex) -> *mut AtomicU32 { rwlock::raw(&m.0) } impl Mutex { pub const fn new() -> Mutex { Mutex(RWLock::new()) } pub unsafe fn init(&mut self) { // This function should normally reinitialize the mutex after // moving it to a different memory address. This implementation // does not require adjustments after moving. } pub unsafe fn try_lock(&self) -> bool { self.0.try_write() } pub unsafe fn
(&self) { self.0.write() } pub unsafe fn unlock(&self) { self.0.write_unlock() } pub unsafe fn destroy(&self) { self.0.destroy() } } pub struct ReentrantMutex { lock: UnsafeCell<AtomicU32>, recursion: UnsafeCell<u32>, } impl ReentrantMutex { pub unsafe fn uninitialized() -> ReentrantMutex { mem::uninitialized() } pub unsafe fn init(&mut self) { self.lock = UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)); self.recursion = UnsafeCell::new(0); } pub unsafe fn try_lock(&self) -> bool { // Attempt to acquire the lock. let lock = self.lock.get(); let recursion = self.recursion.get(); if let Err(old) = (*lock).compare_exchange( abi::LOCK_UNLOCKED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, Ordering::Acquire, Ordering::Relaxed, ) { // If we fail to acquire the lock, it may be the case // that we've already acquired it and may need to recurse. if old & !abi::LOCK_KERNEL_MANAGED.0 == __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0 { *recursion += 1; true } else { false } } else { // Success. assert_eq!(*recursion, 0, "Mutex has invalid recursion count"); true } } pub unsafe fn lock(&self) { if !self.try_lock() { // Call into the kernel to acquire a write lock. let lock = self.lock.get(); let subscription = abi::subscription { type_: abi::eventtype::LOCK_WRLOCK, union: abi::subscription_union { lock: abi::subscription_lock { lock: lock as *mut abi::lock, lock_scope: abi::scope::PRIVATE, }, }, ..mem::zeroed() }; let mut event: abi::event = mem::uninitialized(); let mut nevents: usize = mem::uninitialized(); let ret = abi::poll(&subscription, &mut event, 1, &mut nevents); assert_eq!(ret, abi::errno::SUCCESS, "Failed to acquire mutex"); assert_eq!(event.error, abi::errno::SUCCESS, "Failed to acquire mutex"); } } pub unsafe fn unlock(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed) & !abi::LOCK_KERNEL_MANAGED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, "This mutex is locked by a different thread" ); if *recursion > 0 { *recursion -= 1; } else if !(*lock) .compare_exchange( __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, abi::LOCK_UNLOCKED.0, Ordering::Release, Ordering::Relaxed, ) .is_ok() { // Lock is managed by kernelspace. Call into the kernel // to unblock waiting threads. let ret = abi::lock_unlock(lock as *mut abi::lock, abi::scope::PRIVATE); assert_eq!(ret, abi::errno::SUCCESS, "Failed to unlock a mutex"); } } pub unsafe fn destroy(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed), abi::LOCK_UNLOCKED.0, "Attempted to destroy locked mutex" ); assert_eq!(*recursion, 0, "Recursion counter invalid"); } }
lock
identifier_name
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use cell::UnsafeCell; use mem; use sync::atomic::{AtomicU32, Ordering}; use sys::cloudabi::abi; use sys::rwlock::{self, RWLock}; extern "C" { #[thread_local] static __pthread_thread_id: abi::tid; } // Implement Mutex using an RWLock. This doesn't introduce any // performance overhead in this environment, as the operations would be // implemented identically. pub struct Mutex(RWLock); pub unsafe fn raw(m: &Mutex) -> *mut AtomicU32 { rwlock::raw(&m.0) } impl Mutex { pub const fn new() -> Mutex
pub unsafe fn init(&mut self) { // This function should normally reinitialize the mutex after // moving it to a different memory address. This implementation // does not require adjustments after moving. } pub unsafe fn try_lock(&self) -> bool { self.0.try_write() } pub unsafe fn lock(&self) { self.0.write() } pub unsafe fn unlock(&self) { self.0.write_unlock() } pub unsafe fn destroy(&self) { self.0.destroy() } } pub struct ReentrantMutex { lock: UnsafeCell<AtomicU32>, recursion: UnsafeCell<u32>, } impl ReentrantMutex { pub unsafe fn uninitialized() -> ReentrantMutex { mem::uninitialized() } pub unsafe fn init(&mut self) { self.lock = UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)); self.recursion = UnsafeCell::new(0); } pub unsafe fn try_lock(&self) -> bool { // Attempt to acquire the lock. let lock = self.lock.get(); let recursion = self.recursion.get(); if let Err(old) = (*lock).compare_exchange( abi::LOCK_UNLOCKED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, Ordering::Acquire, Ordering::Relaxed, ) { // If we fail to acquire the lock, it may be the case // that we've already acquired it and may need to recurse. if old & !abi::LOCK_KERNEL_MANAGED.0 == __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0 { *recursion += 1; true } else { false } } else { // Success. assert_eq!(*recursion, 0, "Mutex has invalid recursion count"); true } } pub unsafe fn lock(&self) { if !self.try_lock() { // Call into the kernel to acquire a write lock. let lock = self.lock.get(); let subscription = abi::subscription { type_: abi::eventtype::LOCK_WRLOCK, union: abi::subscription_union { lock: abi::subscription_lock { lock: lock as *mut abi::lock, lock_scope: abi::scope::PRIVATE, }, }, ..mem::zeroed() }; let mut event: abi::event = mem::uninitialized(); let mut nevents: usize = mem::uninitialized(); let ret = abi::poll(&subscription, &mut event, 1, &mut nevents); assert_eq!(ret, abi::errno::SUCCESS, "Failed to acquire mutex"); assert_eq!(event.error, abi::errno::SUCCESS, "Failed to acquire mutex"); } } pub unsafe fn unlock(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed) & !abi::LOCK_KERNEL_MANAGED.0, __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, "This mutex is locked by a different thread" ); if *recursion > 0 { *recursion -= 1; } else if !(*lock) .compare_exchange( __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, abi::LOCK_UNLOCKED.0, Ordering::Release, Ordering::Relaxed, ) .is_ok() { // Lock is managed by kernelspace. Call into the kernel // to unblock waiting threads. let ret = abi::lock_unlock(lock as *mut abi::lock, abi::scope::PRIVATE); assert_eq!(ret, abi::errno::SUCCESS, "Failed to unlock a mutex"); } } pub unsafe fn destroy(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed), abi::LOCK_UNLOCKED.0, "Attempted to destroy locked mutex" ); assert_eq!(*recursion, 0, "Recursion counter invalid"); } }
{ Mutex(RWLock::new()) }
identifier_body
topics.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Help URL topic mappings.""" __author__ = [ 'John Cox (johncox@google.com)', ] class _LegacyUrl(object):
# Mappings. Each row is a (topic_id, url_suffix), where topic_id is a string # containing the unique identifier of the help topic, and url_suffix is a string # giving the suffix of the help URL. Neither may be missing or empty. url_suffix # is relative to the version component of the URL. If you have a URL of the form # # https://www.google.com/edu/openonline/course-builder/docs/1.10/something, # # the value to put here is '/something'. _ALL = [ ('certificate:certificate_criteria', '/prepare-for-students/certificates.html'), ('core_tags:google_drive:unavailable', '/create-a-course/add-content/google-drive.html' '#enable-apis'), ('core_tags:google_group:name', '/create-a-course/add-content/content-editor.html' '#google-group'), ('core_tags:markdown:markdown', '/create-a-course/add-content/content-editor.html' '#markdown'), ('course:advanced:description', '/create-a-course/course-settings.html' '#advanced-course-settings'), ('course:assessment:content', '/create-a-course/add-elements/assessments/assessments.html'), ('course:assessment:html_content', '/create-a-course/add-elements/assessments/assessments.html'), ('course:assessment:review_form', '/create-a-course/add-elements/assessments/peer-review.html' '#reviewer-feedback-form'), ('course:assessment:review_opts', '/create-a-course/add-elements/assessments/peer-review.html' '#peer-review-fields'), ('course:assessment:snippet', '/create-a-course/add-elements/assessments/assessments.html' '#embed-link'), ('course:assessment:workflow:grader', '/create-a-course/add-elements/assessments/assessments.html' '#grading-method'), ('course:auto_index', '/create-a-course/course-settings.html' '#auto-index-course'), ('course:availability:availability', '/publish-a-course/availability.html' '#content-availability'), ('course:availability:shown_when_unavailable', '/publish-a-course/availability.html' '#content-availability'), ('course:can_record_student_events', '/create-a-course/course-settings.html' '#enable-student-analytics'), ('course:can_student_change_locale', '/prepare-for-students/translations/set-up.html' '#show-language-picker'), ('course:google:api_key', '/create-a-course/add-content/google-drive.html' '#get-credentials'), ('course:google:client_id', '/create-a-course/add-content/google-drive.html' '#get-credentials'), ('course:google_analytics_id', '/create-a-course/course-settings.html' '#analytics-id'), ('course:google_tag_manager_id', '/create-a-course/course-settings.html' '#tag-manager-id'), ('course:lesson:activity', '/create-a-course/add-elements/lessons/add-new.html' '#lesson-body'), ('course:lesson:manual_progress', '/create-a-course/add-elements/lessons/settings.html' '#allow-progress-override'), ('course:main_image:url', '/create-a-course/course-settings.html' '#image-or-video'), ('course:unit:manual_progress', '/create-a-course/add-elements/units/details-and-settings.html' '#allow-progress-override'), ('course:welcome_notifications_sender', '/prepare-for-students/registration.html' '#email-sender'), ('dashboard:gift_questions:questions', '/create-a-course/add-elements/questions/formats.html' '#gift-questions'), ('dashboard:powered_by', '/index.html'), ('data_pump:json_key', '/analyze-data/custom-analytics.html' '#data-pump-values'), ('data_pump:pii_encryption_token', '/analyze-data/custom-analytics.html' '#data-pump-values'), ('data_pump:project_id', '/set-up-course-builder/create-a-cloud-project.html' '#set-project-id'), ('data_pump:table_lifetime', '/analyze-data/custom-analytics.html' '#data-pump-values'), ('data_removal:removal_policy', '/create-a-course/course-settings.html' '#removal-policy'), ('help:documentation', '/index.html'), ('help:forum', _LegacyUrl( 'https://groups.google.com/forum/?fromgroups#!categories/' 'course-builder-forum/general-troubleshooting')), ('help:videos', _LegacyUrl( 'https://www.youtube.com/playlist?list=PLFB_aGY5EfxeltJfJZwkjqDLAW' 'dMfSpES')), ('labels:tracks', '/create-a-course/organize-elements/tracks.html'), ('math:math:input_type', '/create-a-course/add-content/content-editor.html' '#math-formula'), ('modules:guide:availability', '/administer-site/guides.html' '#availability'), ('modules:guide:enabled', '/administer-site/guides.html' '#enable-guides'), ('modules:webserv:availability', '/administer-site/web-server.html' '#availability'), ('modules:webserv:doc_root', '/administer-site/web-server.html' '#content-root'), ('modules:webserv:enabled', '/administer-site/web-server.html' '#enable-web-server'), ('questionnaire:questionnaire:disabled', '/create-a-course/add-content/content-editor.html' '#questionnaire'), ('questionnaire:questionnaire:form_id', '/create-a-course/add-content/content-editor.html' '#questionnaire'), ('reg_form:additional_registration_fields', '/prepare-for-students/registration.html' '#registration-questions'), ('settings:debugging:show_hooks', '/debug-course/debug-course.html'), ('settings:debugging:show_jinja_context', '/debug-course/debug-course.html'), ('workflow:review_window_mins', '/create-a-course/add-elements/assessments/peer-review.html' '#review-window-timeout'), ]
"""A legacy URL, where the value is taken verbatim instead of calculated.""" def __init__(self, value): self.value = value
identifier_body
topics.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Help URL topic mappings.""" __author__ = [ 'John Cox (johncox@google.com)', ] class _LegacyUrl(object): """A legacy URL, where the value is taken verbatim instead of calculated.""" def
(self, value): self.value = value # Mappings. Each row is a (topic_id, url_suffix), where topic_id is a string # containing the unique identifier of the help topic, and url_suffix is a string # giving the suffix of the help URL. Neither may be missing or empty. url_suffix # is relative to the version component of the URL. If you have a URL of the form # # https://www.google.com/edu/openonline/course-builder/docs/1.10/something, # # the value to put here is '/something'. _ALL = [ ('certificate:certificate_criteria', '/prepare-for-students/certificates.html'), ('core_tags:google_drive:unavailable', '/create-a-course/add-content/google-drive.html' '#enable-apis'), ('core_tags:google_group:name', '/create-a-course/add-content/content-editor.html' '#google-group'), ('core_tags:markdown:markdown', '/create-a-course/add-content/content-editor.html' '#markdown'), ('course:advanced:description', '/create-a-course/course-settings.html' '#advanced-course-settings'), ('course:assessment:content', '/create-a-course/add-elements/assessments/assessments.html'), ('course:assessment:html_content', '/create-a-course/add-elements/assessments/assessments.html'), ('course:assessment:review_form', '/create-a-course/add-elements/assessments/peer-review.html' '#reviewer-feedback-form'), ('course:assessment:review_opts', '/create-a-course/add-elements/assessments/peer-review.html' '#peer-review-fields'), ('course:assessment:snippet', '/create-a-course/add-elements/assessments/assessments.html' '#embed-link'), ('course:assessment:workflow:grader', '/create-a-course/add-elements/assessments/assessments.html' '#grading-method'), ('course:auto_index', '/create-a-course/course-settings.html' '#auto-index-course'), ('course:availability:availability', '/publish-a-course/availability.html' '#content-availability'), ('course:availability:shown_when_unavailable', '/publish-a-course/availability.html' '#content-availability'), ('course:can_record_student_events', '/create-a-course/course-settings.html' '#enable-student-analytics'), ('course:can_student_change_locale', '/prepare-for-students/translations/set-up.html' '#show-language-picker'), ('course:google:api_key', '/create-a-course/add-content/google-drive.html' '#get-credentials'), ('course:google:client_id', '/create-a-course/add-content/google-drive.html' '#get-credentials'), ('course:google_analytics_id', '/create-a-course/course-settings.html' '#analytics-id'), ('course:google_tag_manager_id', '/create-a-course/course-settings.html' '#tag-manager-id'), ('course:lesson:activity', '/create-a-course/add-elements/lessons/add-new.html' '#lesson-body'), ('course:lesson:manual_progress', '/create-a-course/add-elements/lessons/settings.html' '#allow-progress-override'), ('course:main_image:url', '/create-a-course/course-settings.html' '#image-or-video'), ('course:unit:manual_progress', '/create-a-course/add-elements/units/details-and-settings.html' '#allow-progress-override'), ('course:welcome_notifications_sender', '/prepare-for-students/registration.html' '#email-sender'), ('dashboard:gift_questions:questions', '/create-a-course/add-elements/questions/formats.html' '#gift-questions'), ('dashboard:powered_by', '/index.html'), ('data_pump:json_key', '/analyze-data/custom-analytics.html' '#data-pump-values'), ('data_pump:pii_encryption_token', '/analyze-data/custom-analytics.html' '#data-pump-values'), ('data_pump:project_id', '/set-up-course-builder/create-a-cloud-project.html' '#set-project-id'), ('data_pump:table_lifetime', '/analyze-data/custom-analytics.html' '#data-pump-values'), ('data_removal:removal_policy', '/create-a-course/course-settings.html' '#removal-policy'), ('help:documentation', '/index.html'), ('help:forum', _LegacyUrl( 'https://groups.google.com/forum/?fromgroups#!categories/' 'course-builder-forum/general-troubleshooting')), ('help:videos', _LegacyUrl( 'https://www.youtube.com/playlist?list=PLFB_aGY5EfxeltJfJZwkjqDLAW' 'dMfSpES')), ('labels:tracks', '/create-a-course/organize-elements/tracks.html'), ('math:math:input_type', '/create-a-course/add-content/content-editor.html' '#math-formula'), ('modules:guide:availability', '/administer-site/guides.html' '#availability'), ('modules:guide:enabled', '/administer-site/guides.html' '#enable-guides'), ('modules:webserv:availability', '/administer-site/web-server.html' '#availability'), ('modules:webserv:doc_root', '/administer-site/web-server.html' '#content-root'), ('modules:webserv:enabled', '/administer-site/web-server.html' '#enable-web-server'), ('questionnaire:questionnaire:disabled', '/create-a-course/add-content/content-editor.html' '#questionnaire'), ('questionnaire:questionnaire:form_id', '/create-a-course/add-content/content-editor.html' '#questionnaire'), ('reg_form:additional_registration_fields', '/prepare-for-students/registration.html' '#registration-questions'), ('settings:debugging:show_hooks', '/debug-course/debug-course.html'), ('settings:debugging:show_jinja_context', '/debug-course/debug-course.html'), ('workflow:review_window_mins', '/create-a-course/add-elements/assessments/peer-review.html' '#review-window-timeout'), ]
__init__
identifier_name
topics.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Help URL topic mappings.""" __author__ = [ 'John Cox (johncox@google.com)', ] class _LegacyUrl(object): """A legacy URL, where the value is taken verbatim instead of calculated.""" def __init__(self, value):
# giving the suffix of the help URL. Neither may be missing or empty. url_suffix # is relative to the version component of the URL. If you have a URL of the form # # https://www.google.com/edu/openonline/course-builder/docs/1.10/something, # # the value to put here is '/something'. _ALL = [ ('certificate:certificate_criteria', '/prepare-for-students/certificates.html'), ('core_tags:google_drive:unavailable', '/create-a-course/add-content/google-drive.html' '#enable-apis'), ('core_tags:google_group:name', '/create-a-course/add-content/content-editor.html' '#google-group'), ('core_tags:markdown:markdown', '/create-a-course/add-content/content-editor.html' '#markdown'), ('course:advanced:description', '/create-a-course/course-settings.html' '#advanced-course-settings'), ('course:assessment:content', '/create-a-course/add-elements/assessments/assessments.html'), ('course:assessment:html_content', '/create-a-course/add-elements/assessments/assessments.html'), ('course:assessment:review_form', '/create-a-course/add-elements/assessments/peer-review.html' '#reviewer-feedback-form'), ('course:assessment:review_opts', '/create-a-course/add-elements/assessments/peer-review.html' '#peer-review-fields'), ('course:assessment:snippet', '/create-a-course/add-elements/assessments/assessments.html' '#embed-link'), ('course:assessment:workflow:grader', '/create-a-course/add-elements/assessments/assessments.html' '#grading-method'), ('course:auto_index', '/create-a-course/course-settings.html' '#auto-index-course'), ('course:availability:availability', '/publish-a-course/availability.html' '#content-availability'), ('course:availability:shown_when_unavailable', '/publish-a-course/availability.html' '#content-availability'), ('course:can_record_student_events', '/create-a-course/course-settings.html' '#enable-student-analytics'), ('course:can_student_change_locale', '/prepare-for-students/translations/set-up.html' '#show-language-picker'), ('course:google:api_key', '/create-a-course/add-content/google-drive.html' '#get-credentials'), ('course:google:client_id', '/create-a-course/add-content/google-drive.html' '#get-credentials'), ('course:google_analytics_id', '/create-a-course/course-settings.html' '#analytics-id'), ('course:google_tag_manager_id', '/create-a-course/course-settings.html' '#tag-manager-id'), ('course:lesson:activity', '/create-a-course/add-elements/lessons/add-new.html' '#lesson-body'), ('course:lesson:manual_progress', '/create-a-course/add-elements/lessons/settings.html' '#allow-progress-override'), ('course:main_image:url', '/create-a-course/course-settings.html' '#image-or-video'), ('course:unit:manual_progress', '/create-a-course/add-elements/units/details-and-settings.html' '#allow-progress-override'), ('course:welcome_notifications_sender', '/prepare-for-students/registration.html' '#email-sender'), ('dashboard:gift_questions:questions', '/create-a-course/add-elements/questions/formats.html' '#gift-questions'), ('dashboard:powered_by', '/index.html'), ('data_pump:json_key', '/analyze-data/custom-analytics.html' '#data-pump-values'), ('data_pump:pii_encryption_token', '/analyze-data/custom-analytics.html' '#data-pump-values'), ('data_pump:project_id', '/set-up-course-builder/create-a-cloud-project.html' '#set-project-id'), ('data_pump:table_lifetime', '/analyze-data/custom-analytics.html' '#data-pump-values'), ('data_removal:removal_policy', '/create-a-course/course-settings.html' '#removal-policy'), ('help:documentation', '/index.html'), ('help:forum', _LegacyUrl( 'https://groups.google.com/forum/?fromgroups#!categories/' 'course-builder-forum/general-troubleshooting')), ('help:videos', _LegacyUrl( 'https://www.youtube.com/playlist?list=PLFB_aGY5EfxeltJfJZwkjqDLAW' 'dMfSpES')), ('labels:tracks', '/create-a-course/organize-elements/tracks.html'), ('math:math:input_type', '/create-a-course/add-content/content-editor.html' '#math-formula'), ('modules:guide:availability', '/administer-site/guides.html' '#availability'), ('modules:guide:enabled', '/administer-site/guides.html' '#enable-guides'), ('modules:webserv:availability', '/administer-site/web-server.html' '#availability'), ('modules:webserv:doc_root', '/administer-site/web-server.html' '#content-root'), ('modules:webserv:enabled', '/administer-site/web-server.html' '#enable-web-server'), ('questionnaire:questionnaire:disabled', '/create-a-course/add-content/content-editor.html' '#questionnaire'), ('questionnaire:questionnaire:form_id', '/create-a-course/add-content/content-editor.html' '#questionnaire'), ('reg_form:additional_registration_fields', '/prepare-for-students/registration.html' '#registration-questions'), ('settings:debugging:show_hooks', '/debug-course/debug-course.html'), ('settings:debugging:show_jinja_context', '/debug-course/debug-course.html'), ('workflow:review_window_mins', '/create-a-course/add-elements/assessments/peer-review.html' '#review-window-timeout'), ]
self.value = value # Mappings. Each row is a (topic_id, url_suffix), where topic_id is a string # containing the unique identifier of the help topic, and url_suffix is a string
random_line_split
vera.py
""" Support for Vera sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.vera/ """ import logging from homeassistant.const import ( TEMP_CELSIUS, TEMP_FAHRENHEIT) from homeassistant.helpers.entity import Entity from homeassistant.components.sensor import ENTITY_ID_FORMAT from homeassistant.components.vera import ( VERA_CONTROLLER, VERA_DEVICES, VeraDevice) DEPENDENCIES = ['vera'] _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): """Perform the setup for Vera controller devices.""" add_devices( VeraSensor(device, VERA_CONTROLLER) for device in VERA_DEVICES['sensor']) class VeraSensor(VeraDevice, Entity): """Representation of a Vera Sensor.""" def __init__(self, vera_device, controller): """Initialize the sensor.""" self.current_value = None self._temperature_units = None VeraDevice.__init__(self, vera_device, controller) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) @property def
(self): """Return the name of the sensor.""" return self.current_value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" if self.vera_device.category == "Temperature Sensor": return self._temperature_units elif self.vera_device.category == "Light Sensor": return 'lux' elif self.vera_device.category == "Humidity Sensor": return '%' def update(self): """Update the state.""" if self.vera_device.category == "Temperature Sensor": self.current_value = self.vera_device.temperature vera_temp_units = ( self.vera_device.vera_controller.temperature_units) if vera_temp_units == 'F': self._temperature_units = TEMP_FAHRENHEIT else: self._temperature_units = TEMP_CELSIUS elif self.vera_device.category == "Light Sensor": self.current_value = self.vera_device.light elif self.vera_device.category == "Humidity Sensor": self.current_value = self.vera_device.humidity elif self.vera_device.category == "Sensor": tripped = self.vera_device.is_tripped self.current_value = 'Tripped' if tripped else 'Not Tripped' else: self.current_value = 'Unknown'
state
identifier_name
vera.py
""" Support for Vera sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.vera/ """ import logging from homeassistant.const import ( TEMP_CELSIUS, TEMP_FAHRENHEIT) from homeassistant.helpers.entity import Entity from homeassistant.components.sensor import ENTITY_ID_FORMAT from homeassistant.components.vera import ( VERA_CONTROLLER, VERA_DEVICES, VeraDevice) DEPENDENCIES = ['vera'] _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): """Perform the setup for Vera controller devices.""" add_devices( VeraSensor(device, VERA_CONTROLLER) for device in VERA_DEVICES['sensor']) class VeraSensor(VeraDevice, Entity): """Representation of a Vera Sensor.""" def __init__(self, vera_device, controller):
@property def state(self): """Return the name of the sensor.""" return self.current_value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" if self.vera_device.category == "Temperature Sensor": return self._temperature_units elif self.vera_device.category == "Light Sensor": return 'lux' elif self.vera_device.category == "Humidity Sensor": return '%' def update(self): """Update the state.""" if self.vera_device.category == "Temperature Sensor": self.current_value = self.vera_device.temperature vera_temp_units = ( self.vera_device.vera_controller.temperature_units) if vera_temp_units == 'F': self._temperature_units = TEMP_FAHRENHEIT else: self._temperature_units = TEMP_CELSIUS elif self.vera_device.category == "Light Sensor": self.current_value = self.vera_device.light elif self.vera_device.category == "Humidity Sensor": self.current_value = self.vera_device.humidity elif self.vera_device.category == "Sensor": tripped = self.vera_device.is_tripped self.current_value = 'Tripped' if tripped else 'Not Tripped' else: self.current_value = 'Unknown'
"""Initialize the sensor.""" self.current_value = None self._temperature_units = None VeraDevice.__init__(self, vera_device, controller) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id)
identifier_body
vera.py
""" Support for Vera sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.vera/ """ import logging from homeassistant.const import ( TEMP_CELSIUS, TEMP_FAHRENHEIT) from homeassistant.helpers.entity import Entity from homeassistant.components.sensor import ENTITY_ID_FORMAT from homeassistant.components.vera import ( VERA_CONTROLLER, VERA_DEVICES, VeraDevice) DEPENDENCIES = ['vera'] _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): """Perform the setup for Vera controller devices.""" add_devices( VeraSensor(device, VERA_CONTROLLER) for device in VERA_DEVICES['sensor']) class VeraSensor(VeraDevice, Entity): """Representation of a Vera Sensor.""" def __init__(self, vera_device, controller): """Initialize the sensor.""" self.current_value = None self._temperature_units = None VeraDevice.__init__(self, vera_device, controller) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) @property def state(self): """Return the name of the sensor.""" return self.current_value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" if self.vera_device.category == "Temperature Sensor": return self._temperature_units elif self.vera_device.category == "Light Sensor": return 'lux' elif self.vera_device.category == "Humidity Sensor": return '%' def update(self): """Update the state.""" if self.vera_device.category == "Temperature Sensor": self.current_value = self.vera_device.temperature vera_temp_units = ( self.vera_device.vera_controller.temperature_units) if vera_temp_units == 'F': self._temperature_units = TEMP_FAHRENHEIT else: self._temperature_units = TEMP_CELSIUS elif self.vera_device.category == "Light Sensor": self.current_value = self.vera_device.light elif self.vera_device.category == "Humidity Sensor":
elif self.vera_device.category == "Sensor": tripped = self.vera_device.is_tripped self.current_value = 'Tripped' if tripped else 'Not Tripped' else: self.current_value = 'Unknown'
self.current_value = self.vera_device.humidity
conditional_block
vera.py
""" Support for Vera sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.vera/ """ import logging from homeassistant.const import ( TEMP_CELSIUS, TEMP_FAHRENHEIT) from homeassistant.helpers.entity import Entity from homeassistant.components.sensor import ENTITY_ID_FORMAT from homeassistant.components.vera import ( VERA_CONTROLLER, VERA_DEVICES, VeraDevice) DEPENDENCIES = ['vera'] _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): """Perform the setup for Vera controller devices.""" add_devices( VeraSensor(device, VERA_CONTROLLER) for device in VERA_DEVICES['sensor']) class VeraSensor(VeraDevice, Entity): """Representation of a Vera Sensor.""" def __init__(self, vera_device, controller): """Initialize the sensor.""" self.current_value = None self._temperature_units = None VeraDevice.__init__(self, vera_device, controller) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) @property def state(self): """Return the name of the sensor.""" return self.current_value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" if self.vera_device.category == "Temperature Sensor": return self._temperature_units elif self.vera_device.category == "Light Sensor": return 'lux' elif self.vera_device.category == "Humidity Sensor": return '%' def update(self): """Update the state.""" if self.vera_device.category == "Temperature Sensor": self.current_value = self.vera_device.temperature vera_temp_units = ( self.vera_device.vera_controller.temperature_units)
elif self.vera_device.category == "Light Sensor": self.current_value = self.vera_device.light elif self.vera_device.category == "Humidity Sensor": self.current_value = self.vera_device.humidity elif self.vera_device.category == "Sensor": tripped = self.vera_device.is_tripped self.current_value = 'Tripped' if tripped else 'Not Tripped' else: self.current_value = 'Unknown'
if vera_temp_units == 'F': self._temperature_units = TEMP_FAHRENHEIT else: self._temperature_units = TEMP_CELSIUS
random_line_split
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only full descending stacks are supported. /// Represents the different types of stacks that exist. #[allow(dead_code)] pub enum StackType { /// The value currently pointed to is used and the stack grows downward. FullDescending, /// The value currently pointed to is not used and the stack grows downward. EmptyDescending, /// The value currently pointed to is used and the stack grows upward. FullAscending, /// The value currently pointed to is not used and the stack grows upward. EmptyAscending } /// Determines the type of accesses possible for this stack. #[derive(PartialEq)] pub enum AccessType { /// The stack can be accessed by usermode code. UserAccessible, /// The stack can only be accessed by the kernel. KernelOnly } /// Represents a stack. pub struct Stack { /// Represents the top address of the stack. top_address: VirtualAddress, /// Represents the bottom address of the stack. bottom_address: VirtualAddress, /// Represents the maximum stack size. max_size: usize, /// Represents the first address of the stack. pub base_stack_pointer: VirtualAddress, /// The access type for this stack. access_type: AccessType } impl fmt::Debug for Stack { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Bottom: {:?}, Top: {:?}, Max size: {:x}", self.bottom_address, self.top_address, self.max_size ) } } impl Drop for Stack { fn drop(&mut self) { // NOTE: This assumes that the stack is dropped in its own address space. self.resize(0, None); } } impl Stack { /// Pushes the given value to the stack pointed to in the given address /// space. pub fn push_in<T>( address_space: &mut AddressSpace, stack_pointer: &mut VirtualAddress, value: T ) { match arch::Current::STACK_TYPE { StackType::FullDescending => { *stack_pointer -= size_of::<T>(); unsafe { address_space.write_val(value, *stack_pointer); } }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Creates a new stack of size zero with the given start address. pub fn new( initial_size: usize, max_size: usize, start_address: VirtualAddress, access_type: AccessType, mut address_space: Option<&mut AddressSpace> ) -> Stack { let mut stack = match arch::Current::STACK_TYPE { StackType::FullDescending => Stack { top_address: start_address + max_size, bottom_address: start_address + max_size, max_size, base_stack_pointer: start_address + max_size, access_type }, _ => unimplemented!("Currently only Full Descending stacks are implemented") }; if let Some(ref mut address_space) = address_space { let mut flags = READABLE | WRITABLE; if stack.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let area = MemoryArea::new(start_address, max_size); assert!( address_space.add_segment(Segment::new(area, flags, SegmentType::MemoryOnly)), "Could not add stack segment." ); } stack.resize(initial_size, address_space); stack } /// Grows the stack by the given amount. pub fn grow(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = max( self.top_address - self.max_size, self.bottom_address - amount ); let mut flags = READABLE | WRITABLE; if self.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let first_page_to_map = new_bottom.page_num(); // This should be one less, but the range is exclusive. let last_page_to_map = self.bottom_address.page_num(); // TODO: flags shouldn't be passed, it should be segment checked instead. let mut map_fn = |page_address, flags| match address_space { Some(ref mut address_space) => address_space.map_page(page_address), None => arch::Current::map_page(page_address, flags) }; for page_num in first_page_to_map..last_page_to_map { map_fn(VirtualAddress::from_page_num(page_num), flags); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Shrinks the stack by the given amount. pub fn shrink(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = min(self.top_address, self.bottom_address + amount); let first_page_to_unmap = self.bottom_address.page_num(); // This should be one less, but the range is exclusive. let last_page_to_unmap = new_bottom.page_num(); let mut unmap_fn = |page_address| unsafe { match address_space { Some(ref mut address_space) => address_space.unmap_page(page_address), None => arch::Current::unmap_page(page_address) } }; for page_num in first_page_to_unmap..last_page_to_unmap { unmap_fn(VirtualAddress::from_page_num(page_num)); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Resizes the stack to the given size. pub fn resize(&mut self, new_size: usize, address_space: Option<&mut AddressSpace>)
}
{ let current_size = (self.top_address - self.bottom_address) as isize; let difference = new_size as isize - current_size; if difference > 0 { self.grow(difference as usize, address_space); } else { self.shrink(-difference as usize, address_space); } }
identifier_body
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only full descending stacks are supported. /// Represents the different types of stacks that exist. #[allow(dead_code)] pub enum StackType { /// The value currently pointed to is used and the stack grows downward. FullDescending, /// The value currently pointed to is not used and the stack grows downward. EmptyDescending, /// The value currently pointed to is used and the stack grows upward. FullAscending, /// The value currently pointed to is not used and the stack grows upward. EmptyAscending } /// Determines the type of accesses possible for this stack. #[derive(PartialEq)] pub enum AccessType { /// The stack can be accessed by usermode code. UserAccessible, /// The stack can only be accessed by the kernel. KernelOnly } /// Represents a stack. pub struct Stack { /// Represents the top address of the stack. top_address: VirtualAddress, /// Represents the bottom address of the stack. bottom_address: VirtualAddress, /// Represents the maximum stack size. max_size: usize, /// Represents the first address of the stack. pub base_stack_pointer: VirtualAddress, /// The access type for this stack. access_type: AccessType } impl fmt::Debug for Stack { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Bottom: {:?}, Top: {:?}, Max size: {:x}", self.bottom_address, self.top_address, self.max_size ) } } impl Drop for Stack { fn drop(&mut self) { // NOTE: This assumes that the stack is dropped in its own address space. self.resize(0, None); } } impl Stack { /// Pushes the given value to the stack pointed to in the given address /// space. pub fn push_in<T>( address_space: &mut AddressSpace, stack_pointer: &mut VirtualAddress, value: T ) { match arch::Current::STACK_TYPE { StackType::FullDescending => { *stack_pointer -= size_of::<T>(); unsafe { address_space.write_val(value, *stack_pointer); } }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Creates a new stack of size zero with the given start address. pub fn new( initial_size: usize, max_size: usize, start_address: VirtualAddress, access_type: AccessType, mut address_space: Option<&mut AddressSpace> ) -> Stack { let mut stack = match arch::Current::STACK_TYPE { StackType::FullDescending => Stack { top_address: start_address + max_size, bottom_address: start_address + max_size, max_size, base_stack_pointer: start_address + max_size, access_type }, _ => unimplemented!("Currently only Full Descending stacks are implemented") }; if let Some(ref mut address_space) = address_space { let mut flags = READABLE | WRITABLE; if stack.access_type == AccessType::UserAccessible
let area = MemoryArea::new(start_address, max_size); assert!( address_space.add_segment(Segment::new(area, flags, SegmentType::MemoryOnly)), "Could not add stack segment." ); } stack.resize(initial_size, address_space); stack } /// Grows the stack by the given amount. pub fn grow(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = max( self.top_address - self.max_size, self.bottom_address - amount ); let mut flags = READABLE | WRITABLE; if self.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let first_page_to_map = new_bottom.page_num(); // This should be one less, but the range is exclusive. let last_page_to_map = self.bottom_address.page_num(); // TODO: flags shouldn't be passed, it should be segment checked instead. let mut map_fn = |page_address, flags| match address_space { Some(ref mut address_space) => address_space.map_page(page_address), None => arch::Current::map_page(page_address, flags) }; for page_num in first_page_to_map..last_page_to_map { map_fn(VirtualAddress::from_page_num(page_num), flags); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Shrinks the stack by the given amount. pub fn shrink(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = min(self.top_address, self.bottom_address + amount); let first_page_to_unmap = self.bottom_address.page_num(); // This should be one less, but the range is exclusive. let last_page_to_unmap = new_bottom.page_num(); let mut unmap_fn = |page_address| unsafe { match address_space { Some(ref mut address_space) => address_space.unmap_page(page_address), None => arch::Current::unmap_page(page_address) } }; for page_num in first_page_to_unmap..last_page_to_unmap { unmap_fn(VirtualAddress::from_page_num(page_num)); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Resizes the stack to the given size. pub fn resize(&mut self, new_size: usize, address_space: Option<&mut AddressSpace>) { let current_size = (self.top_address - self.bottom_address) as isize; let difference = new_size as isize - current_size; if difference > 0 { self.grow(difference as usize, address_space); } else { self.shrink(-difference as usize, address_space); } } }
{ flags |= USER_ACCESSIBLE; }
conditional_block
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only full descending stacks are supported. /// Represents the different types of stacks that exist. #[allow(dead_code)] pub enum StackType { /// The value currently pointed to is used and the stack grows downward. FullDescending, /// The value currently pointed to is not used and the stack grows downward. EmptyDescending, /// The value currently pointed to is used and the stack grows upward. FullAscending, /// The value currently pointed to is not used and the stack grows upward. EmptyAscending } /// Determines the type of accesses possible for this stack. #[derive(PartialEq)] pub enum AccessType { /// The stack can be accessed by usermode code. UserAccessible, /// The stack can only be accessed by the kernel. KernelOnly } /// Represents a stack. pub struct Stack { /// Represents the top address of the stack. top_address: VirtualAddress, /// Represents the bottom address of the stack. bottom_address: VirtualAddress, /// Represents the maximum stack size. max_size: usize, /// Represents the first address of the stack. pub base_stack_pointer: VirtualAddress, /// The access type for this stack. access_type: AccessType } impl fmt::Debug for Stack { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f,
"Bottom: {:?}, Top: {:?}, Max size: {:x}", self.bottom_address, self.top_address, self.max_size ) } } impl Drop for Stack { fn drop(&mut self) { // NOTE: This assumes that the stack is dropped in its own address space. self.resize(0, None); } } impl Stack { /// Pushes the given value to the stack pointed to in the given address /// space. pub fn push_in<T>( address_space: &mut AddressSpace, stack_pointer: &mut VirtualAddress, value: T ) { match arch::Current::STACK_TYPE { StackType::FullDescending => { *stack_pointer -= size_of::<T>(); unsafe { address_space.write_val(value, *stack_pointer); } }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Creates a new stack of size zero with the given start address. pub fn new( initial_size: usize, max_size: usize, start_address: VirtualAddress, access_type: AccessType, mut address_space: Option<&mut AddressSpace> ) -> Stack { let mut stack = match arch::Current::STACK_TYPE { StackType::FullDescending => Stack { top_address: start_address + max_size, bottom_address: start_address + max_size, max_size, base_stack_pointer: start_address + max_size, access_type }, _ => unimplemented!("Currently only Full Descending stacks are implemented") }; if let Some(ref mut address_space) = address_space { let mut flags = READABLE | WRITABLE; if stack.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let area = MemoryArea::new(start_address, max_size); assert!( address_space.add_segment(Segment::new(area, flags, SegmentType::MemoryOnly)), "Could not add stack segment." ); } stack.resize(initial_size, address_space); stack } /// Grows the stack by the given amount. pub fn grow(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = max( self.top_address - self.max_size, self.bottom_address - amount ); let mut flags = READABLE | WRITABLE; if self.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let first_page_to_map = new_bottom.page_num(); // This should be one less, but the range is exclusive. let last_page_to_map = self.bottom_address.page_num(); // TODO: flags shouldn't be passed, it should be segment checked instead. let mut map_fn = |page_address, flags| match address_space { Some(ref mut address_space) => address_space.map_page(page_address), None => arch::Current::map_page(page_address, flags) }; for page_num in first_page_to_map..last_page_to_map { map_fn(VirtualAddress::from_page_num(page_num), flags); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Shrinks the stack by the given amount. pub fn shrink(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = min(self.top_address, self.bottom_address + amount); let first_page_to_unmap = self.bottom_address.page_num(); // This should be one less, but the range is exclusive. let last_page_to_unmap = new_bottom.page_num(); let mut unmap_fn = |page_address| unsafe { match address_space { Some(ref mut address_space) => address_space.unmap_page(page_address), None => arch::Current::unmap_page(page_address) } }; for page_num in first_page_to_unmap..last_page_to_unmap { unmap_fn(VirtualAddress::from_page_num(page_num)); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Resizes the stack to the given size. pub fn resize(&mut self, new_size: usize, address_space: Option<&mut AddressSpace>) { let current_size = (self.top_address - self.bottom_address) as isize; let difference = new_size as isize - current_size; if difference > 0 { self.grow(difference as usize, address_space); } else { self.shrink(-difference as usize, address_space); } } }
random_line_split
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only full descending stacks are supported. /// Represents the different types of stacks that exist. #[allow(dead_code)] pub enum StackType { /// The value currently pointed to is used and the stack grows downward. FullDescending, /// The value currently pointed to is not used and the stack grows downward. EmptyDescending, /// The value currently pointed to is used and the stack grows upward. FullAscending, /// The value currently pointed to is not used and the stack grows upward. EmptyAscending } /// Determines the type of accesses possible for this stack. #[derive(PartialEq)] pub enum AccessType { /// The stack can be accessed by usermode code. UserAccessible, /// The stack can only be accessed by the kernel. KernelOnly } /// Represents a stack. pub struct
{ /// Represents the top address of the stack. top_address: VirtualAddress, /// Represents the bottom address of the stack. bottom_address: VirtualAddress, /// Represents the maximum stack size. max_size: usize, /// Represents the first address of the stack. pub base_stack_pointer: VirtualAddress, /// The access type for this stack. access_type: AccessType } impl fmt::Debug for Stack { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Bottom: {:?}, Top: {:?}, Max size: {:x}", self.bottom_address, self.top_address, self.max_size ) } } impl Drop for Stack { fn drop(&mut self) { // NOTE: This assumes that the stack is dropped in its own address space. self.resize(0, None); } } impl Stack { /// Pushes the given value to the stack pointed to in the given address /// space. pub fn push_in<T>( address_space: &mut AddressSpace, stack_pointer: &mut VirtualAddress, value: T ) { match arch::Current::STACK_TYPE { StackType::FullDescending => { *stack_pointer -= size_of::<T>(); unsafe { address_space.write_val(value, *stack_pointer); } }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Creates a new stack of size zero with the given start address. pub fn new( initial_size: usize, max_size: usize, start_address: VirtualAddress, access_type: AccessType, mut address_space: Option<&mut AddressSpace> ) -> Stack { let mut stack = match arch::Current::STACK_TYPE { StackType::FullDescending => Stack { top_address: start_address + max_size, bottom_address: start_address + max_size, max_size, base_stack_pointer: start_address + max_size, access_type }, _ => unimplemented!("Currently only Full Descending stacks are implemented") }; if let Some(ref mut address_space) = address_space { let mut flags = READABLE | WRITABLE; if stack.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let area = MemoryArea::new(start_address, max_size); assert!( address_space.add_segment(Segment::new(area, flags, SegmentType::MemoryOnly)), "Could not add stack segment." ); } stack.resize(initial_size, address_space); stack } /// Grows the stack by the given amount. pub fn grow(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = max( self.top_address - self.max_size, self.bottom_address - amount ); let mut flags = READABLE | WRITABLE; if self.access_type == AccessType::UserAccessible { flags |= USER_ACCESSIBLE; } let first_page_to_map = new_bottom.page_num(); // This should be one less, but the range is exclusive. let last_page_to_map = self.bottom_address.page_num(); // TODO: flags shouldn't be passed, it should be segment checked instead. let mut map_fn = |page_address, flags| match address_space { Some(ref mut address_space) => address_space.map_page(page_address), None => arch::Current::map_page(page_address, flags) }; for page_num in first_page_to_map..last_page_to_map { map_fn(VirtualAddress::from_page_num(page_num), flags); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Shrinks the stack by the given amount. pub fn shrink(&mut self, amount: usize, mut address_space: Option<&mut AddressSpace>) { match arch::Current::STACK_TYPE { StackType::FullDescending => { let new_bottom = min(self.top_address, self.bottom_address + amount); let first_page_to_unmap = self.bottom_address.page_num(); // This should be one less, but the range is exclusive. let last_page_to_unmap = new_bottom.page_num(); let mut unmap_fn = |page_address| unsafe { match address_space { Some(ref mut address_space) => address_space.unmap_page(page_address), None => arch::Current::unmap_page(page_address) } }; for page_num in first_page_to_unmap..last_page_to_unmap { unmap_fn(VirtualAddress::from_page_num(page_num)); } self.bottom_address = new_bottom; }, _ => unimplemented!("Currently only Full Descending stacks are implemented") } } /// Resizes the stack to the given size. pub fn resize(&mut self, new_size: usize, address_space: Option<&mut AddressSpace>) { let current_size = (self.top_address - self.bottom_address) as isize; let difference = new_size as isize - current_size; if difference > 0 { self.grow(difference as usize, address_space); } else { self.shrink(-difference as usize, address_space); } } }
Stack
identifier_name
MetronomeAnimation.ts
/** * MetronomeAnimation
Default coordinate framefor canvas: (0,0)-----> x | | y Where the origin is to the top left of the canvas. The animation uses a translated coordinate frame where the origin is moved down to the right. The y-axis wraps around such that the last 7/8 of a bar are animated as a right-movement from the left edge of the canvas, while the first 7/8 are animated as a right movement from the translated origin. */ const sigma = 0.027; const radius = 10; export default class MetronomeAnimation { private width: number; private height: number; private container: HTMLDivElement; private gridCanvas: HTMLCanvasElement; private ballCanvas: HTMLCanvasElement; private gridContext: CanvasRenderingContext2D; private ballContext: CanvasRenderingContext2D; private animationFrameId: number = 0; private running = false; private nextNote: { progress: number, time: number, tempo: number }; constructor(private getCurrentTime: () => number, private readNoteQue: () => { progress: number, time: number, tempo: number }) { this.container = <HTMLDivElement>document.getElementById('animationContainer'); this.gridCanvas = <HTMLCanvasElement>document.getElementById('bottom-canvas'); this.ballCanvas = <HTMLCanvasElement>document.getElementById('top-canvas'); this.width = this.container.clientWidth * 2; this.height = this.container.clientHeight * 2; this.setSize(this.width, this.height); this.gridContext = this.gridCanvas.getContext('2d'); this.ballContext = this.ballCanvas.getContext('2d'); this.drawPath(); } start() { this.updateNoteInfo(); this.running = true; this.animationFrameId = window.requestAnimationFrame(() => { this.drawBall(); }); } stop() { this.running = false; window.cancelAnimationFrame(this.animationFrameId); } toggle() { if (this.running) { this.stop(); } else { this.start(); } } private setSize(width: number, height: number) { this.gridCanvas.width = width; this.gridCanvas.height = height; this.ballCanvas.width = width; this.ballCanvas.height = height; } private updateNoteInfo() { let data = this.readNoteQue(); if (!data) return; this.nextNote = data; } private transformToNoteFrame(context: CanvasRenderingContext2D) { context.translate(this.width / 8, this.height - radius); } private drawBall() { let ctx = this.ballContext; ctx.clearRect(0, 0, this.width, this.height); ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(51,86,56,0.9)'; ctx.fillStyle = 'rgba(51,86,56,0.5)'; ctx.save(); let barPosition = this.getBarPosition(); this.transformToNoteFrame(ctx); // Translate to desired position ctx.translate(this.getXoffset(barPosition), this.getYoffset(barPosition)); // Add circle path at the place we've translated to this.circle(ctx, radius); // Do stroke ctx.restore(); ctx.stroke(); ctx.fill(); this.animationFrameId = window.requestAnimationFrame(() => { this.drawBall(); }); } private drawPath() { let ctx = this.gridContext; ctx.clearRect(0, 0, this.width, this.height); ctx.lineWidth = 1; ctx.strokeStyle = 'rgb(103,177,104)'; ctx.save(); this.transformToNoteFrame(ctx); let precision = 0.001; // Draw the curve to the right in the note fram for (let barPosition = 0; barPosition < 7 / 8; barPosition += precision) { ctx.lineTo(this.getXoffset(barPosition), this.getYoffset(barPosition)); } // Move to the left side of the canvas ctx.moveTo(this.getXoffset(7 / 8), this.getYoffset(7 / 8)); // Draw the curve to the left in the note fram for (let barPosition = 7 / 8; barPosition < 1; barPosition += precision) { ctx.lineTo(this.getXoffset(barPosition), this.getYoffset(barPosition)); } ctx.restore(); ctx.stroke(); } // Returns percentage of a bar completed. Eg. at exactly two beats it will be 0.5. private getBarPosition(): number { this.updateNoteInfo(); let secondsPerBeat = 60.0 / this.nextNote.tempo; let expectedPosition = this.nextNote.progress - 0.25 * (this.nextNote.time - this.getCurrentTime()) / secondsPerBeat; if (expectedPosition < 0) { expectedPosition = (expectedPosition % 1) + 1; } return expectedPosition; } // How much x should be offset from the origin in the note coordinate frame - implements the wrapping at 7/8 private getXoffset(barPosition: number): number { if (barPosition < 7 / 8) { return barPosition * this.width; } else { return (- 1 / 8 + (barPosition - 7 / 8)) * this.width; } } // How much y should be offset from the origin in the note coordinate frame private getYoffset(barPosition: number): number { let distanceToOrigin = (barPosition > 0.5) ? 1 - barPosition : barPosition; // Gaussian functions to get peaks at the beats let amplitude = 2 * Math.exp(- 0.5 * Math.pow(distanceToOrigin / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.25) / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.50) / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.75) / sigma, 2)); let scaling = - this.height * 1 / 2 * 0.7; return scaling * amplitude; } private circle(context: CanvasRenderingContext2D, radius: number) { context.beginPath(); // Note to self: Adding moveTo here creates a line from center of circle on stroke. context.arc(0, 0, radius, 0, 2 * Math.PI); } }
*/ /*
random_line_split
MetronomeAnimation.ts
/** * MetronomeAnimation */ /* Default coordinate framefor canvas: (0,0)-----> x | | y Where the origin is to the top left of the canvas. The animation uses a translated coordinate frame where the origin is moved down to the right. The y-axis wraps around such that the last 7/8 of a bar are animated as a right-movement from the left edge of the canvas, while the first 7/8 are animated as a right movement from the translated origin. */ const sigma = 0.027; const radius = 10; export default class MetronomeAnimation { private width: number; private height: number; private container: HTMLDivElement; private gridCanvas: HTMLCanvasElement; private ballCanvas: HTMLCanvasElement; private gridContext: CanvasRenderingContext2D; private ballContext: CanvasRenderingContext2D; private animationFrameId: number = 0; private running = false; private nextNote: { progress: number, time: number, tempo: number }; constructor(private getCurrentTime: () => number, private readNoteQue: () => { progress: number, time: number, tempo: number }) { this.container = <HTMLDivElement>document.getElementById('animationContainer'); this.gridCanvas = <HTMLCanvasElement>document.getElementById('bottom-canvas'); this.ballCanvas = <HTMLCanvasElement>document.getElementById('top-canvas'); this.width = this.container.clientWidth * 2; this.height = this.container.clientHeight * 2; this.setSize(this.width, this.height); this.gridContext = this.gridCanvas.getContext('2d'); this.ballContext = this.ballCanvas.getContext('2d'); this.drawPath(); } start()
stop() { this.running = false; window.cancelAnimationFrame(this.animationFrameId); } toggle() { if (this.running) { this.stop(); } else { this.start(); } } private setSize(width: number, height: number) { this.gridCanvas.width = width; this.gridCanvas.height = height; this.ballCanvas.width = width; this.ballCanvas.height = height; } private updateNoteInfo() { let data = this.readNoteQue(); if (!data) return; this.nextNote = data; } private transformToNoteFrame(context: CanvasRenderingContext2D) { context.translate(this.width / 8, this.height - radius); } private drawBall() { let ctx = this.ballContext; ctx.clearRect(0, 0, this.width, this.height); ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(51,86,56,0.9)'; ctx.fillStyle = 'rgba(51,86,56,0.5)'; ctx.save(); let barPosition = this.getBarPosition(); this.transformToNoteFrame(ctx); // Translate to desired position ctx.translate(this.getXoffset(barPosition), this.getYoffset(barPosition)); // Add circle path at the place we've translated to this.circle(ctx, radius); // Do stroke ctx.restore(); ctx.stroke(); ctx.fill(); this.animationFrameId = window.requestAnimationFrame(() => { this.drawBall(); }); } private drawPath() { let ctx = this.gridContext; ctx.clearRect(0, 0, this.width, this.height); ctx.lineWidth = 1; ctx.strokeStyle = 'rgb(103,177,104)'; ctx.save(); this.transformToNoteFrame(ctx); let precision = 0.001; // Draw the curve to the right in the note fram for (let barPosition = 0; barPosition < 7 / 8; barPosition += precision) { ctx.lineTo(this.getXoffset(barPosition), this.getYoffset(barPosition)); } // Move to the left side of the canvas ctx.moveTo(this.getXoffset(7 / 8), this.getYoffset(7 / 8)); // Draw the curve to the left in the note fram for (let barPosition = 7 / 8; barPosition < 1; barPosition += precision) { ctx.lineTo(this.getXoffset(barPosition), this.getYoffset(barPosition)); } ctx.restore(); ctx.stroke(); } // Returns percentage of a bar completed. Eg. at exactly two beats it will be 0.5. private getBarPosition(): number { this.updateNoteInfo(); let secondsPerBeat = 60.0 / this.nextNote.tempo; let expectedPosition = this.nextNote.progress - 0.25 * (this.nextNote.time - this.getCurrentTime()) / secondsPerBeat; if (expectedPosition < 0) { expectedPosition = (expectedPosition % 1) + 1; } return expectedPosition; } // How much x should be offset from the origin in the note coordinate frame - implements the wrapping at 7/8 private getXoffset(barPosition: number): number { if (barPosition < 7 / 8) { return barPosition * this.width; } else { return (- 1 / 8 + (barPosition - 7 / 8)) * this.width; } } // How much y should be offset from the origin in the note coordinate frame private getYoffset(barPosition: number): number { let distanceToOrigin = (barPosition > 0.5) ? 1 - barPosition : barPosition; // Gaussian functions to get peaks at the beats let amplitude = 2 * Math.exp(- 0.5 * Math.pow(distanceToOrigin / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.25) / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.50) / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.75) / sigma, 2)); let scaling = - this.height * 1 / 2 * 0.7; return scaling * amplitude; } private circle(context: CanvasRenderingContext2D, radius: number) { context.beginPath(); // Note to self: Adding moveTo here creates a line from center of circle on stroke. context.arc(0, 0, radius, 0, 2 * Math.PI); } }
{ this.updateNoteInfo(); this.running = true; this.animationFrameId = window.requestAnimationFrame(() => { this.drawBall(); }); }
identifier_body
MetronomeAnimation.ts
/** * MetronomeAnimation */ /* Default coordinate framefor canvas: (0,0)-----> x | | y Where the origin is to the top left of the canvas. The animation uses a translated coordinate frame where the origin is moved down to the right. The y-axis wraps around such that the last 7/8 of a bar are animated as a right-movement from the left edge of the canvas, while the first 7/8 are animated as a right movement from the translated origin. */ const sigma = 0.027; const radius = 10; export default class MetronomeAnimation { private width: number; private height: number; private container: HTMLDivElement; private gridCanvas: HTMLCanvasElement; private ballCanvas: HTMLCanvasElement; private gridContext: CanvasRenderingContext2D; private ballContext: CanvasRenderingContext2D; private animationFrameId: number = 0; private running = false; private nextNote: { progress: number, time: number, tempo: number }; constructor(private getCurrentTime: () => number, private readNoteQue: () => { progress: number, time: number, tempo: number }) { this.container = <HTMLDivElement>document.getElementById('animationContainer'); this.gridCanvas = <HTMLCanvasElement>document.getElementById('bottom-canvas'); this.ballCanvas = <HTMLCanvasElement>document.getElementById('top-canvas'); this.width = this.container.clientWidth * 2; this.height = this.container.clientHeight * 2; this.setSize(this.width, this.height); this.gridContext = this.gridCanvas.getContext('2d'); this.ballContext = this.ballCanvas.getContext('2d'); this.drawPath(); } start() { this.updateNoteInfo(); this.running = true; this.animationFrameId = window.requestAnimationFrame(() => { this.drawBall(); }); } stop() { this.running = false; window.cancelAnimationFrame(this.animationFrameId); } toggle() { if (this.running)
else { this.start(); } } private setSize(width: number, height: number) { this.gridCanvas.width = width; this.gridCanvas.height = height; this.ballCanvas.width = width; this.ballCanvas.height = height; } private updateNoteInfo() { let data = this.readNoteQue(); if (!data) return; this.nextNote = data; } private transformToNoteFrame(context: CanvasRenderingContext2D) { context.translate(this.width / 8, this.height - radius); } private drawBall() { let ctx = this.ballContext; ctx.clearRect(0, 0, this.width, this.height); ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(51,86,56,0.9)'; ctx.fillStyle = 'rgba(51,86,56,0.5)'; ctx.save(); let barPosition = this.getBarPosition(); this.transformToNoteFrame(ctx); // Translate to desired position ctx.translate(this.getXoffset(barPosition), this.getYoffset(barPosition)); // Add circle path at the place we've translated to this.circle(ctx, radius); // Do stroke ctx.restore(); ctx.stroke(); ctx.fill(); this.animationFrameId = window.requestAnimationFrame(() => { this.drawBall(); }); } private drawPath() { let ctx = this.gridContext; ctx.clearRect(0, 0, this.width, this.height); ctx.lineWidth = 1; ctx.strokeStyle = 'rgb(103,177,104)'; ctx.save(); this.transformToNoteFrame(ctx); let precision = 0.001; // Draw the curve to the right in the note fram for (let barPosition = 0; barPosition < 7 / 8; barPosition += precision) { ctx.lineTo(this.getXoffset(barPosition), this.getYoffset(barPosition)); } // Move to the left side of the canvas ctx.moveTo(this.getXoffset(7 / 8), this.getYoffset(7 / 8)); // Draw the curve to the left in the note fram for (let barPosition = 7 / 8; barPosition < 1; barPosition += precision) { ctx.lineTo(this.getXoffset(barPosition), this.getYoffset(barPosition)); } ctx.restore(); ctx.stroke(); } // Returns percentage of a bar completed. Eg. at exactly two beats it will be 0.5. private getBarPosition(): number { this.updateNoteInfo(); let secondsPerBeat = 60.0 / this.nextNote.tempo; let expectedPosition = this.nextNote.progress - 0.25 * (this.nextNote.time - this.getCurrentTime()) / secondsPerBeat; if (expectedPosition < 0) { expectedPosition = (expectedPosition % 1) + 1; } return expectedPosition; } // How much x should be offset from the origin in the note coordinate frame - implements the wrapping at 7/8 private getXoffset(barPosition: number): number { if (barPosition < 7 / 8) { return barPosition * this.width; } else { return (- 1 / 8 + (barPosition - 7 / 8)) * this.width; } } // How much y should be offset from the origin in the note coordinate frame private getYoffset(barPosition: number): number { let distanceToOrigin = (barPosition > 0.5) ? 1 - barPosition : barPosition; // Gaussian functions to get peaks at the beats let amplitude = 2 * Math.exp(- 0.5 * Math.pow(distanceToOrigin / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.25) / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.50) / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.75) / sigma, 2)); let scaling = - this.height * 1 / 2 * 0.7; return scaling * amplitude; } private circle(context: CanvasRenderingContext2D, radius: number) { context.beginPath(); // Note to self: Adding moveTo here creates a line from center of circle on stroke. context.arc(0, 0, radius, 0, 2 * Math.PI); } }
{ this.stop(); }
conditional_block
MetronomeAnimation.ts
/** * MetronomeAnimation */ /* Default coordinate framefor canvas: (0,0)-----> x | | y Where the origin is to the top left of the canvas. The animation uses a translated coordinate frame where the origin is moved down to the right. The y-axis wraps around such that the last 7/8 of a bar are animated as a right-movement from the left edge of the canvas, while the first 7/8 are animated as a right movement from the translated origin. */ const sigma = 0.027; const radius = 10; export default class
{ private width: number; private height: number; private container: HTMLDivElement; private gridCanvas: HTMLCanvasElement; private ballCanvas: HTMLCanvasElement; private gridContext: CanvasRenderingContext2D; private ballContext: CanvasRenderingContext2D; private animationFrameId: number = 0; private running = false; private nextNote: { progress: number, time: number, tempo: number }; constructor(private getCurrentTime: () => number, private readNoteQue: () => { progress: number, time: number, tempo: number }) { this.container = <HTMLDivElement>document.getElementById('animationContainer'); this.gridCanvas = <HTMLCanvasElement>document.getElementById('bottom-canvas'); this.ballCanvas = <HTMLCanvasElement>document.getElementById('top-canvas'); this.width = this.container.clientWidth * 2; this.height = this.container.clientHeight * 2; this.setSize(this.width, this.height); this.gridContext = this.gridCanvas.getContext('2d'); this.ballContext = this.ballCanvas.getContext('2d'); this.drawPath(); } start() { this.updateNoteInfo(); this.running = true; this.animationFrameId = window.requestAnimationFrame(() => { this.drawBall(); }); } stop() { this.running = false; window.cancelAnimationFrame(this.animationFrameId); } toggle() { if (this.running) { this.stop(); } else { this.start(); } } private setSize(width: number, height: number) { this.gridCanvas.width = width; this.gridCanvas.height = height; this.ballCanvas.width = width; this.ballCanvas.height = height; } private updateNoteInfo() { let data = this.readNoteQue(); if (!data) return; this.nextNote = data; } private transformToNoteFrame(context: CanvasRenderingContext2D) { context.translate(this.width / 8, this.height - radius); } private drawBall() { let ctx = this.ballContext; ctx.clearRect(0, 0, this.width, this.height); ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(51,86,56,0.9)'; ctx.fillStyle = 'rgba(51,86,56,0.5)'; ctx.save(); let barPosition = this.getBarPosition(); this.transformToNoteFrame(ctx); // Translate to desired position ctx.translate(this.getXoffset(barPosition), this.getYoffset(barPosition)); // Add circle path at the place we've translated to this.circle(ctx, radius); // Do stroke ctx.restore(); ctx.stroke(); ctx.fill(); this.animationFrameId = window.requestAnimationFrame(() => { this.drawBall(); }); } private drawPath() { let ctx = this.gridContext; ctx.clearRect(0, 0, this.width, this.height); ctx.lineWidth = 1; ctx.strokeStyle = 'rgb(103,177,104)'; ctx.save(); this.transformToNoteFrame(ctx); let precision = 0.001; // Draw the curve to the right in the note fram for (let barPosition = 0; barPosition < 7 / 8; barPosition += precision) { ctx.lineTo(this.getXoffset(barPosition), this.getYoffset(barPosition)); } // Move to the left side of the canvas ctx.moveTo(this.getXoffset(7 / 8), this.getYoffset(7 / 8)); // Draw the curve to the left in the note fram for (let barPosition = 7 / 8; barPosition < 1; barPosition += precision) { ctx.lineTo(this.getXoffset(barPosition), this.getYoffset(barPosition)); } ctx.restore(); ctx.stroke(); } // Returns percentage of a bar completed. Eg. at exactly two beats it will be 0.5. private getBarPosition(): number { this.updateNoteInfo(); let secondsPerBeat = 60.0 / this.nextNote.tempo; let expectedPosition = this.nextNote.progress - 0.25 * (this.nextNote.time - this.getCurrentTime()) / secondsPerBeat; if (expectedPosition < 0) { expectedPosition = (expectedPosition % 1) + 1; } return expectedPosition; } // How much x should be offset from the origin in the note coordinate frame - implements the wrapping at 7/8 private getXoffset(barPosition: number): number { if (barPosition < 7 / 8) { return barPosition * this.width; } else { return (- 1 / 8 + (barPosition - 7 / 8)) * this.width; } } // How much y should be offset from the origin in the note coordinate frame private getYoffset(barPosition: number): number { let distanceToOrigin = (barPosition > 0.5) ? 1 - barPosition : barPosition; // Gaussian functions to get peaks at the beats let amplitude = 2 * Math.exp(- 0.5 * Math.pow(distanceToOrigin / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.25) / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.50) / sigma, 2)); amplitude += Math.exp(- 0.5 * Math.pow((barPosition - 0.75) / sigma, 2)); let scaling = - this.height * 1 / 2 * 0.7; return scaling * amplitude; } private circle(context: CanvasRenderingContext2D, radius: number) { context.beginPath(); // Note to self: Adding moveTo here creates a line from center of circle on stroke. context.arc(0, 0, radius, 0, 2 * Math.PI); } }
MetronomeAnimation
identifier_name
basic.test.ts
import { isEqual } from 'lodash' import { nanoid } from 'nanoid' import { Client, createWaitForResponseMiddleware } from '@resolve-js/client' import { getClient } from '../../utils/utils' let client: Client beforeEach(() => { client = getClient() }) const registerUser = async (userId: string) => client.command({ type: 'register', aggregateName: 'user', aggregateId: userId, payload: { name: 'John Doe', }, }) const waitForUserProfile = async (userId: string, data: object) => { let lastResult = null try { return await client.query( { name: 'users', resolver: 'profile', args: { userId, }, }, { middleware: { response: createWaitForResponseMiddleware({ validator: async (response, confirm) => { const result = await response.json() if (isEqual(result.data, data))
}, attempts: 5, period: 3000, }), }, } ) } catch (e) { // eslint-disable-next-line no-console console.error(lastResult) throw e } } test('execute register command and check the result', async () => { const userId = nanoid() const result = await registerUser(userId) expect(result).toBeDefined() }) test('execute read-model query and check the result', async () => { const userId = nanoid() await registerUser(userId) await waitForUserProfile(userId, { userId, profile: { name: 'John Doe' }, }) })
{ confirm(result) }
conditional_block
basic.test.ts
import { isEqual } from 'lodash' import { nanoid } from 'nanoid' import { Client, createWaitForResponseMiddleware } from '@resolve-js/client' import { getClient } from '../../utils/utils' let client: Client beforeEach(() => { client = getClient() }) const registerUser = async (userId: string) => client.command({ type: 'register', aggregateName: 'user', aggregateId: userId, payload: { name: 'John Doe', }, }) const waitForUserProfile = async (userId: string, data: object) => { let lastResult = null try { return await client.query( { name: 'users', resolver: 'profile', args: { userId,
response: createWaitForResponseMiddleware({ validator: async (response, confirm) => { const result = await response.json() if (isEqual(result.data, data)) { confirm(result) } }, attempts: 5, period: 3000, }), }, } ) } catch (e) { // eslint-disable-next-line no-console console.error(lastResult) throw e } } test('execute register command and check the result', async () => { const userId = nanoid() const result = await registerUser(userId) expect(result).toBeDefined() }) test('execute read-model query and check the result', async () => { const userId = nanoid() await registerUser(userId) await waitForUserProfile(userId, { userId, profile: { name: 'John Doe' }, }) })
}, }, { middleware: {
random_line_split
ClassRegister.js
Ext.define('Desktop.controller.ClassRegister', { extend: 'Deft.mvc.ViewController', inject: ['sharedStorage'], requires: [], config: { sharedStorage: null, descrizione: null, istituto: null, anno_Scolastico:null, classe: null, docente: null, materia: null }, control: { view: { show: 'onShow' }, classRegisterTabPanel: { tabchange: 'onClassRegisterTabPanelChange' }, printRegisterButton: { click: 'onClickPrintRegisterButton' }, studentsGrid: true, teachersGrid: true, signaturesGrid: true, lessonsGrid: true, notesGrid: true, scheduleGrid: true, scheduleGridWeek:{ change : 'onChangeScheduleGridWeek' }, teachersScheduleGrid: true, teachersScheduleGridWeek:{ change : 'onChangeTeachersScheduleGridWeek' } }, onShow: function() { var view = this.getView(); var sharedStorage = this.getSharedStorage(); this.setDescrizione(sharedStorage.sl_descrizione); this.setIstituto(sharedStorage.sl_istituto); this.setAnno_Scolastico(sharedStorage.sl_anno_scolastico); this.setClasse(sharedStorage.sl_classe); this.setDocente(sharedStorage.sl_docente); this.setMateria(sharedStorage.sl_materia); if (Ext.isEmpty(this.getClasse())){ Desktop.ux.window.Notification.info(i18n.important, i18n.workspace_required_class); view.destroy(); } else{ if (Ext.isEmpty(this.getDocente()))
else{ if (Ext.isEmpty(this.getMateria())){ Desktop.ux.window.Notification.info(i18n.important, i18n.workspace_required_subject); view.destroy(); } else{ // ho tutto il necessario preparo la finistra view.setTitle(i18n.teacher_register_title + " - " + this.getDescrizione()); this.getStudentsGrid().getStore().load({ params: { classe:this.getClasse() } }); this.getSignaturesGrid().getStore().load({ params: { classe:this.getClasse(), docente:this.getDocente() } }); this.getLessonsGrid().getStore().load({ params: { classe:this.getClasse(), docente:this.getDocente(), materia:this.getMateria() } }); } } } }, onClassRegisterTabPanelChange: function ( tabPanel, newCard, oldCard, eOpts ) { // do nothing }, onClickPrintRegisterButton: function ( button, e, eOpts ){ var istituto = this.getIstituto(); var anno_scolastico = this.getAnno_Scolastico(); var classe = this.getClasse(); var url = app_context_path + "/print/registroDiClasse/" + istituto + "/" + anno_scolastico + "/" + classe; window.open(url, i18n.class_register_title); }, onChangeScheduleGridWeek: function ( combo, newValue, oldValue, eOpts ){ }, onChangeTeachersScheduleGridWeek: function ( combo, newValue, oldValue, eOpts ){ } });
{ Desktop.ux.window.Notification.info(i18n.important, i18n.workspace_required_teacher); view.destroy(); }
conditional_block
ClassRegister.js
Ext.define('Desktop.controller.ClassRegister', { extend: 'Deft.mvc.ViewController', inject: ['sharedStorage'], requires: [], config: { sharedStorage: null, descrizione: null, istituto: null, anno_Scolastico:null, classe: null, docente: null, materia: null }, control: { view: { show: 'onShow' }, classRegisterTabPanel: { tabchange: 'onClassRegisterTabPanelChange' }, printRegisterButton: { click: 'onClickPrintRegisterButton' }, studentsGrid: true, teachersGrid: true, signaturesGrid: true, lessonsGrid: true, notesGrid: true, scheduleGrid: true, scheduleGridWeek:{ change : 'onChangeScheduleGridWeek' }, teachersScheduleGrid: true, teachersScheduleGridWeek:{ change : 'onChangeTeachersScheduleGridWeek' } }, onShow: function() { var view = this.getView(); var sharedStorage = this.getSharedStorage(); this.setDescrizione(sharedStorage.sl_descrizione); this.setIstituto(sharedStorage.sl_istituto); this.setAnno_Scolastico(sharedStorage.sl_anno_scolastico); this.setClasse(sharedStorage.sl_classe); this.setDocente(sharedStorage.sl_docente); this.setMateria(sharedStorage.sl_materia); if (Ext.isEmpty(this.getClasse())){ Desktop.ux.window.Notification.info(i18n.important, i18n.workspace_required_class); view.destroy(); } else{ if (Ext.isEmpty(this.getDocente())){ Desktop.ux.window.Notification.info(i18n.important, i18n.workspace_required_teacher); view.destroy(); } else{ if (Ext.isEmpty(this.getMateria())){ Desktop.ux.window.Notification.info(i18n.important, i18n.workspace_required_subject); view.destroy(); } else{ // ho tutto il necessario preparo la finistra view.setTitle(i18n.teacher_register_title + " - " + this.getDescrizione()); this.getStudentsGrid().getStore().load({ params: { classe:this.getClasse() } }); this.getSignaturesGrid().getStore().load({ params: { classe:this.getClasse(), docente:this.getDocente() } }); this.getLessonsGrid().getStore().load({ params: { classe:this.getClasse(), docente:this.getDocente(), materia:this.getMateria() } }); } } } }, onClassRegisterTabPanelChange: function ( tabPanel, newCard, oldCard, eOpts ) { // do nothing }, onClickPrintRegisterButton: function ( button, e, eOpts ){
window.open(url, i18n.class_register_title); }, onChangeScheduleGridWeek: function ( combo, newValue, oldValue, eOpts ){ }, onChangeTeachersScheduleGridWeek: function ( combo, newValue, oldValue, eOpts ){ } });
var istituto = this.getIstituto(); var anno_scolastico = this.getAnno_Scolastico(); var classe = this.getClasse(); var url = app_context_path + "/print/registroDiClasse/" + istituto + "/" + anno_scolastico + "/" + classe;
random_line_split
exposer.js
import { FieldErrorProcessor } from "./processors/field-error-processor"; import { RuleResolver } from "./rulesets/rule-resolver"; import { ValidationGroupBuilder } from "./builders/validation-group-builder"; import { ruleRegistry } from "./rule-registry-setup"; import { RulesetBuilder } from "./builders/ruleset-builder"; import { DefaultLocaleHandler } from "./localization/default-locale-handler"; import { locale as defaultLocale } from "./locales/en-us"; import { Ruleset } from "./rulesets/ruleset"; const defaultLocaleCode = "en-us"; const defaultLocaleHandler = new DefaultLocaleHandler(); defaultLocaleHandler.registerLocale(defaultLocaleCode, defaultLocale); defaultLocaleHandler.useLocale(defaultLocaleCode);
return rulesetBuilder.create(basedUpon); } export function mergeRulesets(rulesetA, rulesetB) { const newRuleset = new Ruleset(); newRuleset.rules = Object.assign({}, rulesetA.rules, rulesetB.rules); newRuleset.compositeRules = Object.assign({}, rulesetA.compositeRules, rulesetB.compositeRules); newRuleset.propertyDisplayNames = Object.assign({}, rulesetA.propertyDisplayNames, rulesetB.propertyDisplayNames); return newRuleset; } export function createGroup() { return new ValidationGroupBuilder(fieldErrorProcessor, ruleResolver, defaultLocaleHandler).create(); } export const localeHandler = defaultLocaleHandler; export function supplementLocale(localeCode, localeResource) { defaultLocaleHandler.supplementLocaleFrom(localeCode, localeResource); }
const fieldErrorProcessor = new FieldErrorProcessor(ruleRegistry, defaultLocaleHandler); const ruleResolver = new RuleResolver(); export function createRuleset(basedUpon, withRuleVerification = false) { const rulesetBuilder = withRuleVerification ? new RulesetBuilder(ruleRegistry) : new RulesetBuilder();
random_line_split
exposer.js
import { FieldErrorProcessor } from "./processors/field-error-processor"; import { RuleResolver } from "./rulesets/rule-resolver"; import { ValidationGroupBuilder } from "./builders/validation-group-builder"; import { ruleRegistry } from "./rule-registry-setup"; import { RulesetBuilder } from "./builders/ruleset-builder"; import { DefaultLocaleHandler } from "./localization/default-locale-handler"; import { locale as defaultLocale } from "./locales/en-us"; import { Ruleset } from "./rulesets/ruleset"; const defaultLocaleCode = "en-us"; const defaultLocaleHandler = new DefaultLocaleHandler(); defaultLocaleHandler.registerLocale(defaultLocaleCode, defaultLocale); defaultLocaleHandler.useLocale(defaultLocaleCode); const fieldErrorProcessor = new FieldErrorProcessor(ruleRegistry, defaultLocaleHandler); const ruleResolver = new RuleResolver(); export function createRuleset(basedUpon, withRuleVerification = false) { const rulesetBuilder = withRuleVerification ? new RulesetBuilder(ruleRegistry) : new RulesetBuilder(); return rulesetBuilder.create(basedUpon); } export function
(rulesetA, rulesetB) { const newRuleset = new Ruleset(); newRuleset.rules = Object.assign({}, rulesetA.rules, rulesetB.rules); newRuleset.compositeRules = Object.assign({}, rulesetA.compositeRules, rulesetB.compositeRules); newRuleset.propertyDisplayNames = Object.assign({}, rulesetA.propertyDisplayNames, rulesetB.propertyDisplayNames); return newRuleset; } export function createGroup() { return new ValidationGroupBuilder(fieldErrorProcessor, ruleResolver, defaultLocaleHandler).create(); } export const localeHandler = defaultLocaleHandler; export function supplementLocale(localeCode, localeResource) { defaultLocaleHandler.supplementLocaleFrom(localeCode, localeResource); }
mergeRulesets
identifier_name
exposer.js
import { FieldErrorProcessor } from "./processors/field-error-processor"; import { RuleResolver } from "./rulesets/rule-resolver"; import { ValidationGroupBuilder } from "./builders/validation-group-builder"; import { ruleRegistry } from "./rule-registry-setup"; import { RulesetBuilder } from "./builders/ruleset-builder"; import { DefaultLocaleHandler } from "./localization/default-locale-handler"; import { locale as defaultLocale } from "./locales/en-us"; import { Ruleset } from "./rulesets/ruleset"; const defaultLocaleCode = "en-us"; const defaultLocaleHandler = new DefaultLocaleHandler(); defaultLocaleHandler.registerLocale(defaultLocaleCode, defaultLocale); defaultLocaleHandler.useLocale(defaultLocaleCode); const fieldErrorProcessor = new FieldErrorProcessor(ruleRegistry, defaultLocaleHandler); const ruleResolver = new RuleResolver(); export function createRuleset(basedUpon, withRuleVerification = false) { const rulesetBuilder = withRuleVerification ? new RulesetBuilder(ruleRegistry) : new RulesetBuilder(); return rulesetBuilder.create(basedUpon); } export function mergeRulesets(rulesetA, rulesetB) { const newRuleset = new Ruleset(); newRuleset.rules = Object.assign({}, rulesetA.rules, rulesetB.rules); newRuleset.compositeRules = Object.assign({}, rulesetA.compositeRules, rulesetB.compositeRules); newRuleset.propertyDisplayNames = Object.assign({}, rulesetA.propertyDisplayNames, rulesetB.propertyDisplayNames); return newRuleset; } export function createGroup() { return new ValidationGroupBuilder(fieldErrorProcessor, ruleResolver, defaultLocaleHandler).create(); } export const localeHandler = defaultLocaleHandler; export function supplementLocale(localeCode, localeResource)
{ defaultLocaleHandler.supplementLocaleFrom(localeCode, localeResource); }
identifier_body
show_reply_thumbnails.js
//================================================ // show_reply_thumbnails.js // Author: @iihoshi //================================================
var my_filename = 'show_reply_thumbnails.js'; // プラグイン情報 ここから // プラグイン情報の初期化 if (!jn.pluginInfo) jn.pluginInfo = {}; // プラグイン情報本体 jn.pluginInfo[my_filename.split('.')[0]] = { 'name' : { 'ja' : 'リプライサムネイル表示', 'en' : 'Show thumbnails in reply chain' }, 'author' : { 'en' : '@iihoshi' }, 'version' : '1.0.1', 'file' : my_filename, 'language' : ['en', 'ja'], 'last_update' : "2015/9/24", 'update_timezone' : '9', 'jnVersion' : '4.3.1.0', 'description' : { 'ja' : 'リプライにサムネイル画像があれば表示します。', 'en' : 'Shows thumbnails if a tweet in a reply chain has them.' }, 'updateinfo' : 'http://www.colorless-sight.jp/archives/JanetterPluginUpdateInfo.txt' }; // プラグイン情報ここまで if ((_Janetter_Window_Type != "main") && (_Janetter_Window_Type != "profile")) { return; } function initForThumbnail() { var orig_janetterThumbnail = $.fn.janetterThumbnail.toString(); var re_siblings = /_content\.siblings\('div\.tweet-thumb'\);$/m; var re_find = /_content\.find\('div\.tweet-body /gm; if (!re_siblings.test(orig_janetterThumbnail) || !re_find.test(orig_janetterThumbnail)) { return false; } var replaced = orig_janetterThumbnail .replace(re_siblings, "_content.children('div.tweet-thumb');") .replace(re_find, "_content.find('div.tweet-reply-body "); // console.log(replaced); eval('$.fn.janetterThumbnailForReply = ' + replaced); var tnMouseOverHandler = function () { var $this = $(this), tweet_reply = $this.parents('div.tweet-reply:first'); $this.unbind('mouseover', tnMouseOverHandler); if (tweet_reply.length > 0) { tweet_reply.janetterThumbnailForReply($this.attr('href')); } }; $.fn.janetterThumbnailForReplyEventSet = function () { this.bind('mouseover', tnMouseOverHandler); return this; }; return true; } function initForExpandUrl() { var orig_jn_expandUrl = jn.expandUrl.toString(); var re_tweet_content = /div\.tweet-content:first/m; var re_janetterThumbnail = /\.janetterThumbnail(\W)/gm; if (!re_tweet_content.test(orig_jn_expandUrl) || !re_janetterThumbnail.test(orig_jn_expandUrl)) { return false; } var replaced = orig_jn_expandUrl .replace(re_tweet_content, 'div.tweet-reply:first') .replace(re_janetterThumbnail, '.janetterThumbnailForReply$1'); // console.log(replaced); eval('var expandUrl = ' + replaced); var euMouseOverHandler = function () { var $this = $(this); $this.unbind('mouseover', euMouseOverHandler); expandUrl($this); } $.fn.janetterExpandUrlForReplyEventSet = function () { this.bind('mouseover', euMouseOverHandler); return this; } return true; } // 本プラグインの初期化処理(onInitializeDone 時) function initOnInitialized() { if (!initForThumbnail() || !initForExpandUrl()) { new jn.msgdialog({ title: my_filename, icon: '', message: 'Sorry, ' + my_filename+ ' cannot be installed.', buttons: [ janet.msg.ok ], }); return; } var orig_generateReply = jn.generateReply; jn.generateReply = function (item, is_default) { var reply = orig_generateReply(item, is_default); reply.append('<div class="tweet-thumb"/>'); var a = reply.find('.tweet-reply-body > p.text').children('a.link'); a.janetterExpandUrlForReplyEventSet(); if (jn.conf.disp_thumbnail == 'over') a.janetterThumbnailForReplyEventSet(); else reply.janetterThumbnailForReply(a); return reply; }; console.log(my_filename + ' has been initialized.'); } if (jn.temp.initialized) { // The original onInitializeDone() has already been called! initOnInitialized(); } else { var orig_onInitializeDone = jn.onInitializeDone; jn.onInitializeDone = function () { orig_onInitializeDone && orig_onInitializeDone.apply(this, arguments); initOnInitialized(); }; } })(jQuery, janet);
(function ($, jn) {
random_line_split
show_reply_thumbnails.js
//================================================ // show_reply_thumbnails.js // Author: @iihoshi //================================================ (function ($, jn) { var my_filename = 'show_reply_thumbnails.js'; // プラグイン情報 ここから // プラグイン情報の初期化 if (!jn.pluginInfo) jn.pluginInfo = {}; // プラグイン情報本体 jn.pluginInfo[my_filename.split('.')[0]] = { 'name' : { 'ja' : 'リプライサムネイル表示', 'en' : 'Show thumbnails in reply chain' }, 'author' : { 'en' : '@iihoshi' }, 'version' : '1.0.1', 'file' : my_filename, 'language' : ['en', 'ja'], 'last_update' : "2015/9/24", 'update_timezone' : '9', 'jnVersion' : '4.3.1.0', 'description' : { 'ja' : 'リプライにサムネイル画像があれば表示します。', 'en' : 'Shows thumbnails if a tweet in a reply chain has them.' }, 'updateinfo' : 'http://www.colorless-sight.jp/archives/JanetterPluginUpdateInfo.txt' }; // プラグイン情報ここまで if ((_Janetter_Window_Type != "main") && (_Janetter_Window_Type != "profile")) { return; } function initForThumbnail() { var orig_janetterThumbnail = $.fn.janetterThumbnail.toString(); var re_siblings = /_content\.siblings\('div\.tweet-thumb'\);$
d = /_content\.find\('div\.tweet-body /gm; if (!re_siblings.test(orig_janetterThumbnail) || !re_find.test(orig_janetterThumbnail)) { return false; } var replaced = orig_janetterThumbnail .replace(re_siblings, "_content.children('div.tweet-thumb');") .replace(re_find, "_content.find('div.tweet-reply-body "); // console.log(replaced); eval('$.fn.janetterThumbnailForReply = ' + replaced); var tnMouseOverHandler = function () { var $this = $(this), tweet_reply = $this.parents('div.tweet-reply:first'); $this.unbind('mouseover', tnMouseOverHandler); if (tweet_reply.length > 0) { tweet_reply.janetterThumbnailForReply($this.attr('href')); } }; $.fn.janetterThumbnailForReplyEventSet = function () { this.bind('mouseover', tnMouseOverHandler); return this; }; return true; } function initForExpandUrl() { var orig_jn_expandUrl = jn.expandUrl.toString(); var re_tweet_content = /div\.tweet-content:first/m; var re_janetterThumbnail = /\.janetterThumbnail(\W)/gm; if (!re_tweet_content.test(orig_jn_expandUrl) || !re_janetterThumbnail.test(orig_jn_expandUrl)) { return false; } var replaced = orig_jn_expandUrl .replace(re_tweet_content, 'div.tweet-reply:first') .replace(re_janetterThumbnail, '.janetterThumbnailForReply$1'); // console.log(replaced); eval('var expandUrl = ' + replaced); var euMouseOverHandler = function () { var $this = $(this); $this.unbind('mouseover', euMouseOverHandler); expandUrl($this); } $.fn.janetterExpandUrlForReplyEventSet = function () { this.bind('mouseover', euMouseOverHandler); return this; } return true; } // 本プラグインの初期化処理(onInitializeDone 時) function initOnInitialized() { if (!initForThumbnail() || !initForExpandUrl()) { new jn.msgdialog({ title: my_filename, icon: '', message: 'Sorry, ' + my_filename+ ' cannot be installed.', buttons: [ janet.msg.ok ], }); return; } var orig_generateReply = jn.generateReply; jn.generateReply = function (item, is_default) { var reply = orig_generateReply(item, is_default); reply.append('<div class="tweet-thumb"/>'); var a = reply.find('.tweet-reply-body > p.text').children('a.link'); a.janetterExpandUrlForReplyEventSet(); if (jn.conf.disp_thumbnail == 'over') a.janetterThumbnailForReplyEventSet(); else reply.janetterThumbnailForReply(a); return reply; }; console.log(my_filename + ' has been initialized.'); } if (jn.temp.initialized) { // The original onInitializeDone() has already been called! initOnInitialized(); } else { var orig_onInitializeDone = jn.onInitializeDone; jn.onInitializeDone = function () { orig_onInitializeDone && orig_onInitializeDone.apply(this, arguments); initOnInitialized(); }; } })(jQuery, janet);
/m; var re_fin
identifier_name
show_reply_thumbnails.js
//================================================ // show_reply_thumbnails.js // Author: @iihoshi //================================================ (function ($, jn) { var my_filename = 'show_reply_thumbnails.js'; // プラグイン情報 ここから // プラグイン情報の初期化 if (!jn.pluginInfo) jn.pluginInfo = {}; // プラグイン情報本体 jn.pluginInfo[my_filename.split('.')[0]] = { 'name' : { 'ja' : 'リプライサムネイル表示', 'en' : 'Show thumbnails in reply chain' }, 'author' : { 'en' : '@iihoshi' }, 'version' : '1.0.1', 'file' : my_filename, 'language' : ['en', 'ja'], 'last_update' : "2015/9/24", 'update_timezone' : '9', 'jnVersion' : '4.3.1.0', 'description' : { 'ja' : 'リプライにサムネイル画像があれば表示します。', 'en' : 'Shows thumbnails if a tweet in a reply chain has them.' }, 'updateinfo' : 'http://www.colorless-sight.jp/archives/JanetterPluginUpdateInfo.txt' }; // プラグイン情報ここまで if ((_Janetter_Window_Type != "main") && (_Janetter_Window_Type != "profile")) { return; } function initForThumbnail() { var orig_janetterThumbnail = $.fn.janetterThumbnail.toString(); var re_siblings = /_content\.siblings\('div\.tweet-thumb'\);$/m; var re_find = /_content\.find\('div\.tweet-body /gm; if (!re_siblings.test(orig_janetterThumbnail) || !re_find.test(orig_janetterThumbnail)) { return false; } var replaced = orig_janetterThumbnail .replace(re_siblings, "_content.children('div.tweet-thumb');") .replace(re_find, "_content.find('div.tweet-reply-body "); // console.log(replaced); eval('$.fn.janetterThumbnailForReply = ' + replaced); var tnMouseOverHandler = function () { var $this = $(this), tweet_reply = $this.parents('div.tweet-reply:first'); $this.unbind('mouseover', tnMouseOverHandler); if (tweet_reply.length > 0) { tweet_reply.janetterThumbnailForReply($this.attr('href')); } }; $.fn.janetterThumbnailForReplyEventSet = function () { this.bind('mouseover', tnMouseOverHandler); return this; }; return true; } function initForExpandUrl() { var orig_jn_expandUrl = jn.expandUrl.toString(); var re_tweet_content = /div\.tweet-content:first/m; var re_janetterThumbnail = /\.janetterThu
itle: my_filename, icon: '', message: 'Sorry, ' + my_filename+ ' cannot be installed.', buttons: [ janet.msg.ok ], }); return; } var orig_generateReply = jn.generateReply; jn.generateReply = function (item, is_default) { var reply = orig_generateReply(item, is_default); reply.append('<div class="tweet-thumb"/>'); var a = reply.find('.tweet-reply-body > p.text').children('a.link'); a.janetterExpandUrlForReplyEventSet(); if (jn.conf.disp_thumbnail == 'over') a.janetterThumbnailForReplyEventSet(); else reply.janetterThumbnailForReply(a); return reply; }; console.log(my_filename + ' has been initialized.'); } if (jn.temp.initialized) { // The original onInitializeDone() has already been called! initOnInitialized(); } else { var orig_onInitializeDone = jn.onInitializeDone; jn.onInitializeDone = function () { orig_onInitializeDone && orig_onInitializeDone.apply(this, arguments); initOnInitialized(); }; } })(jQuery, janet);
mbnail(\W)/gm; if (!re_tweet_content.test(orig_jn_expandUrl) || !re_janetterThumbnail.test(orig_jn_expandUrl)) { return false; } var replaced = orig_jn_expandUrl .replace(re_tweet_content, 'div.tweet-reply:first') .replace(re_janetterThumbnail, '.janetterThumbnailForReply$1'); // console.log(replaced); eval('var expandUrl = ' + replaced); var euMouseOverHandler = function () { var $this = $(this); $this.unbind('mouseover', euMouseOverHandler); expandUrl($this); } $.fn.janetterExpandUrlForReplyEventSet = function () { this.bind('mouseover', euMouseOverHandler); return this; } return true; } // 本プラグインの初期化処理(onInitializeDone 時) function initOnInitialized() { if (!initForThumbnail() || !initForExpandUrl()) { new jn.msgdialog({ t
identifier_body
backup_unittest.py
#!/usr/bin/python # # Copyright (C) 2013 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Tests for LUBackup*""" from ganeti import constants from ganeti import objects from ganeti import opcodes from ganeti import query from testsupport import * import testutils class TestLUBackupPrepare(CmdlibTestCase): @patchUtils("instance_utils") def testPrepareLocalExport(self, utils): utils.ReadOneLineFile.return_value = "cluster_secret" inst = self.cfg.AddNewInstance() op = opcodes.OpBackupPrepare(instance_name=inst.name, mode=constants.EXPORT_MODE_LOCAL) self.ExecOpCode(op) @patchUtils("instance_utils") def testPrepareRemoteExport(self, utils): utils.ReadOneLineFile.return_value = "cluster_secret" inst = self.cfg.AddNewInstance() self.rpc.call_x509_cert_create.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(inst.primary_node, ("key_name", testutils.ReadTestData("cert1.pem"))) op = opcodes.OpBackupPrepare(instance_name=inst.name, mode=constants.EXPORT_MODE_REMOTE) self.ExecOpCode(op) class TestLUBackupExportBase(CmdlibTestCase): def setUp(self): super(TestLUBackupExportBase, self).setUp() self.rpc.call_instance_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, True) self.rpc.call_blockdev_assemble.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, ("/dev/mock_path", "/dev/mock_link_name", None)) self.rpc.call_blockdev_shutdown.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) self.rpc.call_blockdev_snapshot.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, ("mock_vg", "mock_id")) self.rpc.call_blockdev_remove.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) self.rpc.call_export_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, "export_daemon") def ImpExpStatus(node_uuid, name): return self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(node_uuid, [objects.ImportExportStatus( exit_status=0 )]) self.rpc.call_impexp_status.side_effect = ImpExpStatus def ImpExpCleanup(node_uuid, name): return self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(node_uuid) self.rpc.call_impexp_cleanup.side_effect = ImpExpCleanup self.rpc.call_finalize_export.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) def testRemoveRunningInstanceWithoutShutdown(self): inst = self.cfg.AddNewInstance(admin_state=constants.ADMINST_UP) op = opcodes.OpBackupExport(instance_name=inst.name, target_node=self.master.name, shutdown=False, remove_instance=True) self.ExecOpCodeExpectOpPrereqError( op, "Can not remove instance without shutting it down before") def testUnsupportedDiskTemplate(self): inst = self.cfg.AddNewInstance(disk_template=constants.DT_FILE) op = opcodes.OpBackupExport(instance_name=inst.name, target_node=self.master.name) self.ExecOpCodeExpectOpPrereqError( op, "Export not supported for instances with file-based disks") class TestLUBackupExportLocalExport(TestLUBackupExportBase): def setUp(self): super(TestLUBackupExportLocalExport, self).setUp() self.inst = self.cfg.AddNewInstance() self.target_node = self.cfg.AddNewNode() self.op = opcodes.OpBackupExport(mode=constants.EXPORT_MODE_LOCAL, instance_name=self.inst.name, target_node=self.target_node.name) self.rpc.call_import_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.target_node, "import_daemon") def testExportWithShutdown(self): inst = self.cfg.AddNewInstance(admin_state=constants.ADMINST_UP) op = self.CopyOpCode(self.op, instance_name=inst.name, shutdown=True) self.ExecOpCode(op) def testExportDeactivatedDisks(self): self.ExecOpCode(self.op) def testExportRemoveInstance(self): op = self.CopyOpCode(self.op, remove_instance=True) self.ExecOpCode(op) def testValidCompressionTool(self): op = self.CopyOpCode(self.op, compress="lzop") self.cfg.SetCompressionTools(["gzip", "lzop"]) self.ExecOpCode(op) def testInvalidCompressionTool(self): op = self.CopyOpCode(self.op, compress="invalid") self.cfg.SetCompressionTools(["gzip", "lzop"]) self.ExecOpCodeExpectOpPrereqError(op, "Compression tool not allowed") class TestLUBackupExportRemoteExport(TestLUBackupExportBase): def setUp(self): super(TestLUBackupExportRemoteExport, self).setUp() self.inst = self.cfg.AddNewInstance() self.op = opcodes.OpBackupExport(mode=constants.EXPORT_MODE_REMOTE, instance_name=self.inst.name, target_node=[], x509_key_name=["mock_key_name"], destination_x509_ca="mock_dest_ca") def testRemoteExportWithoutX509KeyName(self): op = self.CopyOpCode(self.op, x509_key_name=self.REMOVE) self.ExecOpCodeExpectOpPrereqError(op, "Missing X509 key name for encryption") def testRemoteExportWithoutX509DestCa(self): op = self.CopyOpCode(self.op, destination_x509_ca=self.REMOVE) self.ExecOpCodeExpectOpPrereqError(op, "Missing destination X509 CA") if __name__ == "__main__":
testutils.GanetiTestProgram()
conditional_block
backup_unittest.py
#!/usr/bin/python # # Copyright (C) 2013 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Tests for LUBackup*""" from ganeti import constants from ganeti import objects from ganeti import opcodes from ganeti import query from testsupport import * import testutils class TestLUBackupPrepare(CmdlibTestCase): @patchUtils("instance_utils") def testPrepareLocalExport(self, utils): utils.ReadOneLineFile.return_value = "cluster_secret" inst = self.cfg.AddNewInstance() op = opcodes.OpBackupPrepare(instance_name=inst.name, mode=constants.EXPORT_MODE_LOCAL) self.ExecOpCode(op) @patchUtils("instance_utils") def testPrepareRemoteExport(self, utils): utils.ReadOneLineFile.return_value = "cluster_secret" inst = self.cfg.AddNewInstance() self.rpc.call_x509_cert_create.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(inst.primary_node, ("key_name", testutils.ReadTestData("cert1.pem"))) op = opcodes.OpBackupPrepare(instance_name=inst.name, mode=constants.EXPORT_MODE_REMOTE) self.ExecOpCode(op) class TestLUBackupExportBase(CmdlibTestCase): def setUp(self): super(TestLUBackupExportBase, self).setUp() self.rpc.call_instance_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, True) self.rpc.call_blockdev_assemble.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, ("/dev/mock_path", "/dev/mock_link_name", None)) self.rpc.call_blockdev_shutdown.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) self.rpc.call_blockdev_snapshot.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, ("mock_vg", "mock_id")) self.rpc.call_blockdev_remove.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) self.rpc.call_export_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, "export_daemon") def ImpExpStatus(node_uuid, name): return self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(node_uuid, [objects.ImportExportStatus( exit_status=0 )]) self.rpc.call_impexp_status.side_effect = ImpExpStatus def ImpExpCleanup(node_uuid, name): return self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(node_uuid) self.rpc.call_impexp_cleanup.side_effect = ImpExpCleanup self.rpc.call_finalize_export.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) def testRemoveRunningInstanceWithoutShutdown(self): inst = self.cfg.AddNewInstance(admin_state=constants.ADMINST_UP) op = opcodes.OpBackupExport(instance_name=inst.name, target_node=self.master.name, shutdown=False, remove_instance=True) self.ExecOpCodeExpectOpPrereqError( op, "Can not remove instance without shutting it down before") def testUnsupportedDiskTemplate(self):
class TestLUBackupExportLocalExport(TestLUBackupExportBase): def setUp(self): super(TestLUBackupExportLocalExport, self).setUp() self.inst = self.cfg.AddNewInstance() self.target_node = self.cfg.AddNewNode() self.op = opcodes.OpBackupExport(mode=constants.EXPORT_MODE_LOCAL, instance_name=self.inst.name, target_node=self.target_node.name) self.rpc.call_import_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.target_node, "import_daemon") def testExportWithShutdown(self): inst = self.cfg.AddNewInstance(admin_state=constants.ADMINST_UP) op = self.CopyOpCode(self.op, instance_name=inst.name, shutdown=True) self.ExecOpCode(op) def testExportDeactivatedDisks(self): self.ExecOpCode(self.op) def testExportRemoveInstance(self): op = self.CopyOpCode(self.op, remove_instance=True) self.ExecOpCode(op) def testValidCompressionTool(self): op = self.CopyOpCode(self.op, compress="lzop") self.cfg.SetCompressionTools(["gzip", "lzop"]) self.ExecOpCode(op) def testInvalidCompressionTool(self): op = self.CopyOpCode(self.op, compress="invalid") self.cfg.SetCompressionTools(["gzip", "lzop"]) self.ExecOpCodeExpectOpPrereqError(op, "Compression tool not allowed") class TestLUBackupExportRemoteExport(TestLUBackupExportBase): def setUp(self): super(TestLUBackupExportRemoteExport, self).setUp() self.inst = self.cfg.AddNewInstance() self.op = opcodes.OpBackupExport(mode=constants.EXPORT_MODE_REMOTE, instance_name=self.inst.name, target_node=[], x509_key_name=["mock_key_name"], destination_x509_ca="mock_dest_ca") def testRemoteExportWithoutX509KeyName(self): op = self.CopyOpCode(self.op, x509_key_name=self.REMOVE) self.ExecOpCodeExpectOpPrereqError(op, "Missing X509 key name for encryption") def testRemoteExportWithoutX509DestCa(self): op = self.CopyOpCode(self.op, destination_x509_ca=self.REMOVE) self.ExecOpCodeExpectOpPrereqError(op, "Missing destination X509 CA") if __name__ == "__main__": testutils.GanetiTestProgram()
inst = self.cfg.AddNewInstance(disk_template=constants.DT_FILE) op = opcodes.OpBackupExport(instance_name=inst.name, target_node=self.master.name) self.ExecOpCodeExpectOpPrereqError( op, "Export not supported for instances with file-based disks")
identifier_body
backup_unittest.py
#!/usr/bin/python # # Copyright (C) 2013 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Tests for LUBackup*""" from ganeti import constants from ganeti import objects from ganeti import opcodes from ganeti import query from testsupport import * import testutils class TestLUBackupPrepare(CmdlibTestCase): @patchUtils("instance_utils") def testPrepareLocalExport(self, utils): utils.ReadOneLineFile.return_value = "cluster_secret" inst = self.cfg.AddNewInstance() op = opcodes.OpBackupPrepare(instance_name=inst.name, mode=constants.EXPORT_MODE_LOCAL) self.ExecOpCode(op) @patchUtils("instance_utils") def testPrepareRemoteExport(self, utils): utils.ReadOneLineFile.return_value = "cluster_secret" inst = self.cfg.AddNewInstance() self.rpc.call_x509_cert_create.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(inst.primary_node, ("key_name", testutils.ReadTestData("cert1.pem"))) op = opcodes.OpBackupPrepare(instance_name=inst.name, mode=constants.EXPORT_MODE_REMOTE) self.ExecOpCode(op) class TestLUBackupExportBase(CmdlibTestCase): def setUp(self): super(TestLUBackupExportBase, self).setUp() self.rpc.call_instance_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, True) self.rpc.call_blockdev_assemble.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, ("/dev/mock_path", "/dev/mock_link_name", None)) self.rpc.call_blockdev_shutdown.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) self.rpc.call_blockdev_snapshot.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, ("mock_vg", "mock_id")) self.rpc.call_blockdev_remove.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) self.rpc.call_export_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, "export_daemon") def ImpExpStatus(node_uuid, name): return self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(node_uuid, [objects.ImportExportStatus( exit_status=0 )]) self.rpc.call_impexp_status.side_effect = ImpExpStatus def ImpExpCleanup(node_uuid, name): return self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(node_uuid) self.rpc.call_impexp_cleanup.side_effect = ImpExpCleanup self.rpc.call_finalize_export.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) def testRemoveRunningInstanceWithoutShutdown(self): inst = self.cfg.AddNewInstance(admin_state=constants.ADMINST_UP) op = opcodes.OpBackupExport(instance_name=inst.name, target_node=self.master.name, shutdown=False, remove_instance=True) self.ExecOpCodeExpectOpPrereqError( op, "Can not remove instance without shutting it down before") def testUnsupportedDiskTemplate(self): inst = self.cfg.AddNewInstance(disk_template=constants.DT_FILE) op = opcodes.OpBackupExport(instance_name=inst.name, target_node=self.master.name) self.ExecOpCodeExpectOpPrereqError( op, "Export not supported for instances with file-based disks") class TestLUBackupExportLocalExport(TestLUBackupExportBase): def setUp(self): super(TestLUBackupExportLocalExport, self).setUp() self.inst = self.cfg.AddNewInstance() self.target_node = self.cfg.AddNewNode() self.op = opcodes.OpBackupExport(mode=constants.EXPORT_MODE_LOCAL, instance_name=self.inst.name, target_node=self.target_node.name) self.rpc.call_import_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.target_node, "import_daemon") def testExportWithShutdown(self): inst = self.cfg.AddNewInstance(admin_state=constants.ADMINST_UP) op = self.CopyOpCode(self.op, instance_name=inst.name, shutdown=True) self.ExecOpCode(op) def testExportDeactivatedDisks(self): self.ExecOpCode(self.op) def testExportRemoveInstance(self): op = self.CopyOpCode(self.op, remove_instance=True) self.ExecOpCode(op) def testValidCompressionTool(self): op = self.CopyOpCode(self.op, compress="lzop") self.cfg.SetCompressionTools(["gzip", "lzop"]) self.ExecOpCode(op) def
(self): op = self.CopyOpCode(self.op, compress="invalid") self.cfg.SetCompressionTools(["gzip", "lzop"]) self.ExecOpCodeExpectOpPrereqError(op, "Compression tool not allowed") class TestLUBackupExportRemoteExport(TestLUBackupExportBase): def setUp(self): super(TestLUBackupExportRemoteExport, self).setUp() self.inst = self.cfg.AddNewInstance() self.op = opcodes.OpBackupExport(mode=constants.EXPORT_MODE_REMOTE, instance_name=self.inst.name, target_node=[], x509_key_name=["mock_key_name"], destination_x509_ca="mock_dest_ca") def testRemoteExportWithoutX509KeyName(self): op = self.CopyOpCode(self.op, x509_key_name=self.REMOVE) self.ExecOpCodeExpectOpPrereqError(op, "Missing X509 key name for encryption") def testRemoteExportWithoutX509DestCa(self): op = self.CopyOpCode(self.op, destination_x509_ca=self.REMOVE) self.ExecOpCodeExpectOpPrereqError(op, "Missing destination X509 CA") if __name__ == "__main__": testutils.GanetiTestProgram()
testInvalidCompressionTool
identifier_name
backup_unittest.py
#!/usr/bin/python # # Copyright (C) 2013 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Tests for LUBackup*""" from ganeti import constants from ganeti import objects from ganeti import opcodes from ganeti import query from testsupport import * import testutils class TestLUBackupPrepare(CmdlibTestCase): @patchUtils("instance_utils") def testPrepareLocalExport(self, utils): utils.ReadOneLineFile.return_value = "cluster_secret" inst = self.cfg.AddNewInstance() op = opcodes.OpBackupPrepare(instance_name=inst.name, mode=constants.EXPORT_MODE_LOCAL) self.ExecOpCode(op) @patchUtils("instance_utils") def testPrepareRemoteExport(self, utils): utils.ReadOneLineFile.return_value = "cluster_secret" inst = self.cfg.AddNewInstance() self.rpc.call_x509_cert_create.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(inst.primary_node, ("key_name", testutils.ReadTestData("cert1.pem"))) op = opcodes.OpBackupPrepare(instance_name=inst.name, mode=constants.EXPORT_MODE_REMOTE) self.ExecOpCode(op) class TestLUBackupExportBase(CmdlibTestCase): def setUp(self): super(TestLUBackupExportBase, self).setUp() self.rpc.call_instance_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, True) self.rpc.call_blockdev_assemble.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, ("/dev/mock_path", "/dev/mock_link_name", None)) self.rpc.call_blockdev_shutdown.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) self.rpc.call_blockdev_snapshot.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, ("mock_vg", "mock_id")) self.rpc.call_blockdev_remove.return_value = \ self.RpcResultsBuilder() \
self.rpc.call_export_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, "export_daemon") def ImpExpStatus(node_uuid, name): return self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(node_uuid, [objects.ImportExportStatus( exit_status=0 )]) self.rpc.call_impexp_status.side_effect = ImpExpStatus def ImpExpCleanup(node_uuid, name): return self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(node_uuid) self.rpc.call_impexp_cleanup.side_effect = ImpExpCleanup self.rpc.call_finalize_export.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, None) def testRemoveRunningInstanceWithoutShutdown(self): inst = self.cfg.AddNewInstance(admin_state=constants.ADMINST_UP) op = opcodes.OpBackupExport(instance_name=inst.name, target_node=self.master.name, shutdown=False, remove_instance=True) self.ExecOpCodeExpectOpPrereqError( op, "Can not remove instance without shutting it down before") def testUnsupportedDiskTemplate(self): inst = self.cfg.AddNewInstance(disk_template=constants.DT_FILE) op = opcodes.OpBackupExport(instance_name=inst.name, target_node=self.master.name) self.ExecOpCodeExpectOpPrereqError( op, "Export not supported for instances with file-based disks") class TestLUBackupExportLocalExport(TestLUBackupExportBase): def setUp(self): super(TestLUBackupExportLocalExport, self).setUp() self.inst = self.cfg.AddNewInstance() self.target_node = self.cfg.AddNewNode() self.op = opcodes.OpBackupExport(mode=constants.EXPORT_MODE_LOCAL, instance_name=self.inst.name, target_node=self.target_node.name) self.rpc.call_import_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.target_node, "import_daemon") def testExportWithShutdown(self): inst = self.cfg.AddNewInstance(admin_state=constants.ADMINST_UP) op = self.CopyOpCode(self.op, instance_name=inst.name, shutdown=True) self.ExecOpCode(op) def testExportDeactivatedDisks(self): self.ExecOpCode(self.op) def testExportRemoveInstance(self): op = self.CopyOpCode(self.op, remove_instance=True) self.ExecOpCode(op) def testValidCompressionTool(self): op = self.CopyOpCode(self.op, compress="lzop") self.cfg.SetCompressionTools(["gzip", "lzop"]) self.ExecOpCode(op) def testInvalidCompressionTool(self): op = self.CopyOpCode(self.op, compress="invalid") self.cfg.SetCompressionTools(["gzip", "lzop"]) self.ExecOpCodeExpectOpPrereqError(op, "Compression tool not allowed") class TestLUBackupExportRemoteExport(TestLUBackupExportBase): def setUp(self): super(TestLUBackupExportRemoteExport, self).setUp() self.inst = self.cfg.AddNewInstance() self.op = opcodes.OpBackupExport(mode=constants.EXPORT_MODE_REMOTE, instance_name=self.inst.name, target_node=[], x509_key_name=["mock_key_name"], destination_x509_ca="mock_dest_ca") def testRemoteExportWithoutX509KeyName(self): op = self.CopyOpCode(self.op, x509_key_name=self.REMOVE) self.ExecOpCodeExpectOpPrereqError(op, "Missing X509 key name for encryption") def testRemoteExportWithoutX509DestCa(self): op = self.CopyOpCode(self.op, destination_x509_ca=self.REMOVE) self.ExecOpCodeExpectOpPrereqError(op, "Missing destination X509 CA") if __name__ == "__main__": testutils.GanetiTestProgram()
.CreateSuccessfulNodeResult(self.master, None)
random_line_split
index.js
import Botkit from 'botkit'; import os from 'os'; import Wit from 'botkit-middleware-witai'; import moment from 'moment-timezone'; import models from '../../app/models'; import storageCreator from '../lib/storage'; import setupReceiveMiddleware from '../middleware/receiveMiddleware'; import notWitController from './notWit'; import miscController from './misc'; import sessionsController from './sessions'; import pingsController from './pings'; import slashController from './slash'; import dashboardController from './dashboard'; import { seedAndUpdateUsers } from '../../app/scripts'; require('dotenv').config(); var env = process.env.NODE_ENV || 'development'; if (env == 'development') { process.env.SLACK_ID = process.env.DEV_SLACK_ID; process.env.SLACK_SECRET = process.env.DEV_SLACK_SECRET; } // actions import { firstInstallInitiateConversation, loginInitiateConversation } from '../actions'; // Wit Brain if (process.env.WIT_TOKEN) { var wit = Wit({ token: process.env.WIT_TOKEN, minimum_confidence: 0.55 }); } else { console.log('Error: Specify WIT_TOKEN in environment'); process.exit(1); } export { wit }; /** * *** CONFIG **** */ var config = {}; const storage = storageCreator(config); var controller = Botkit.slackbot({ interactive_replies: true, storage }); export { controller }; /** * User has joined slack channel ==> make connection * then onboard! */ controller.on('team_join', function (bot, message) { console.log("\n\n\n ~~ joined the team ~~ \n\n\n"); const SlackUserId = message.user.id; console.log(message.user.id); bot.api.users.info({ user: SlackUserId }, (err, response) => { if (!err) { const { user, user: { id, team_id, name, tz } } = response; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); }); /** * User has updated data ==> update our DB! */ controller.on('user_change', function (bot, message) { console.log("\n\n\n ~~ user updated profile ~~ \n\n\n"); if (message && message.user) { const { user, user: { name, id, team_id, tz } } = message; const SlackUserId = id; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); // simple way to keep track of bots export var bots = {}; if (!process.env.SLACK_ID || !process.env.SLACK_SECRET || !process.env.HTTP_PORT) { console.log('Error: Specify SLACK_ID SLACK_SECRET and HTTP_PORT in environment'); process.exit(1); } // Custom Toki Config export function customConfigBot(controller) { // beef up the bot setupReceiveMiddleware(controller); notWitController(controller); dashboardController(controller); pingsController(controller); sessionsController(controller); slashController(controller); miscController(controller); } // try to avoid repeat RTM's export function trackBot(bot) { bots[bot.config.token] = bot; } /** * *** TURN ON THE BOT **** * VIA SIGNUP OR LOGIN */ export function connectOnInstall(team_config) { console.log(`\n\n\n\n CONNECTING ON INSTALL \n\n\n\n`); let bot = controller.spawn(team_config); controller.trigger('create_bot', [bot, team_config]); } export function
(identity) { // bot already exists, get bot token for this users team var SlackUserId = identity.user_id; var TeamId = identity.team_id; models.Team.find({ where: { TeamId } }) .then((team) => { const { token } = team; if (token) { var bot = controller.spawn({ token }); controller.trigger('login_bot', [bot, identity]); } }) } controller.on('rtm_open',function(bot) { console.log(`\n\n\n\n** The RTM api just connected! for bot token: ${bot.config.token}\n\n\n`); }); // upon install controller.on('create_bot', (bot,team) => { const { id, url, name, bot: { token, user_id, createdBy, accessToken, scopes } } = team; // this is what is used to save team data const teamConfig = { TeamId: id, createdBy, url, name, token, scopes, accessToken } if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! restarting bot due to re-install"); // restart the bot bots[bot.config.token].closeRTM(); } bot.startRTM((err) => { if (!err) { console.log("\n\n RTM on with team install and listening \n\n"); trackBot(bot); controller.saveTeam(teamConfig, (err, id) => { if (err) { console.log("Error saving team") } else { console.log("Team " + team.name + " saved"); console.log(`\n\n installing users... \n\n`); bot.api.users.list({}, (err, response) => { if (!err) { const { members } = response; seedAndUpdateUsers(members); } firstInstallInitiateConversation(bot, team); }); } }); } else { console.log("RTM failed") } }); }); // subsequent logins controller.on('login_bot', (bot,identity) => { if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! do nothing."); loginInitiateConversation(bot, identity); } else { bot.startRTM((err) => { if (!err) { console.log("RTM on and listening"); trackBot(bot); loginInitiateConversation(bot, identity); } else { console.log("RTM failed") console.log(err); } }); } });
connectOnLogin
identifier_name
index.js
import Botkit from 'botkit'; import os from 'os'; import Wit from 'botkit-middleware-witai'; import moment from 'moment-timezone'; import models from '../../app/models'; import storageCreator from '../lib/storage'; import setupReceiveMiddleware from '../middleware/receiveMiddleware'; import notWitController from './notWit'; import miscController from './misc'; import sessionsController from './sessions'; import pingsController from './pings'; import slashController from './slash'; import dashboardController from './dashboard'; import { seedAndUpdateUsers } from '../../app/scripts'; require('dotenv').config(); var env = process.env.NODE_ENV || 'development'; if (env == 'development') { process.env.SLACK_ID = process.env.DEV_SLACK_ID; process.env.SLACK_SECRET = process.env.DEV_SLACK_SECRET; } // actions import { firstInstallInitiateConversation, loginInitiateConversation } from '../actions'; // Wit Brain if (process.env.WIT_TOKEN) { var wit = Wit({ token: process.env.WIT_TOKEN, minimum_confidence: 0.55 }); } else { console.log('Error: Specify WIT_TOKEN in environment'); process.exit(1); } export { wit }; /** * *** CONFIG **** */ var config = {}; const storage = storageCreator(config); var controller = Botkit.slackbot({ interactive_replies: true, storage }); export { controller }; /** * User has joined slack channel ==> make connection * then onboard! */ controller.on('team_join', function (bot, message) { console.log("\n\n\n ~~ joined the team ~~ \n\n\n"); const SlackUserId = message.user.id; console.log(message.user.id); bot.api.users.info({ user: SlackUserId }, (err, response) => { if (!err) { const { user, user: { id, team_id, name, tz } } = response; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); }); /** * User has updated data ==> update our DB! */ controller.on('user_change', function (bot, message) { console.log("\n\n\n ~~ user updated profile ~~ \n\n\n"); if (message && message.user) { const { user, user: { name, id, team_id, tz } } = message; const SlackUserId = id; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); // simple way to keep track of bots export var bots = {}; if (!process.env.SLACK_ID || !process.env.SLACK_SECRET || !process.env.HTTP_PORT) { console.log('Error: Specify SLACK_ID SLACK_SECRET and HTTP_PORT in environment'); process.exit(1); } // Custom Toki Config export function customConfigBot(controller) { // beef up the bot setupReceiveMiddleware(controller); notWitController(controller); dashboardController(controller); pingsController(controller); sessionsController(controller); slashController(controller); miscController(controller); } // try to avoid repeat RTM's export function trackBot(bot) { bots[bot.config.token] = bot; } /** * *** TURN ON THE BOT **** * VIA SIGNUP OR LOGIN */ export function connectOnInstall(team_config) { console.log(`\n\n\n\n CONNECTING ON INSTALL \n\n\n\n`); let bot = controller.spawn(team_config); controller.trigger('create_bot', [bot, team_config]); } export function connectOnLogin(identity)
controller.on('rtm_open',function(bot) { console.log(`\n\n\n\n** The RTM api just connected! for bot token: ${bot.config.token}\n\n\n`); }); // upon install controller.on('create_bot', (bot,team) => { const { id, url, name, bot: { token, user_id, createdBy, accessToken, scopes } } = team; // this is what is used to save team data const teamConfig = { TeamId: id, createdBy, url, name, token, scopes, accessToken } if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! restarting bot due to re-install"); // restart the bot bots[bot.config.token].closeRTM(); } bot.startRTM((err) => { if (!err) { console.log("\n\n RTM on with team install and listening \n\n"); trackBot(bot); controller.saveTeam(teamConfig, (err, id) => { if (err) { console.log("Error saving team") } else { console.log("Team " + team.name + " saved"); console.log(`\n\n installing users... \n\n`); bot.api.users.list({}, (err, response) => { if (!err) { const { members } = response; seedAndUpdateUsers(members); } firstInstallInitiateConversation(bot, team); }); } }); } else { console.log("RTM failed") } }); }); // subsequent logins controller.on('login_bot', (bot,identity) => { if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! do nothing."); loginInitiateConversation(bot, identity); } else { bot.startRTM((err) => { if (!err) { console.log("RTM on and listening"); trackBot(bot); loginInitiateConversation(bot, identity); } else { console.log("RTM failed") console.log(err); } }); } });
{ // bot already exists, get bot token for this users team var SlackUserId = identity.user_id; var TeamId = identity.team_id; models.Team.find({ where: { TeamId } }) .then((team) => { const { token } = team; if (token) { var bot = controller.spawn({ token }); controller.trigger('login_bot', [bot, identity]); } }) }
identifier_body
index.js
import Botkit from 'botkit'; import os from 'os'; import Wit from 'botkit-middleware-witai'; import moment from 'moment-timezone'; import models from '../../app/models'; import storageCreator from '../lib/storage'; import setupReceiveMiddleware from '../middleware/receiveMiddleware'; import notWitController from './notWit'; import miscController from './misc'; import sessionsController from './sessions'; import pingsController from './pings'; import slashController from './slash'; import dashboardController from './dashboard'; import { seedAndUpdateUsers } from '../../app/scripts'; require('dotenv').config(); var env = process.env.NODE_ENV || 'development'; if (env == 'development') { process.env.SLACK_ID = process.env.DEV_SLACK_ID; process.env.SLACK_SECRET = process.env.DEV_SLACK_SECRET; } // actions import { firstInstallInitiateConversation, loginInitiateConversation } from '../actions'; // Wit Brain if (process.env.WIT_TOKEN) { var wit = Wit({ token: process.env.WIT_TOKEN, minimum_confidence: 0.55 }); } else { console.log('Error: Specify WIT_TOKEN in environment'); process.exit(1); } export { wit }; /** * *** CONFIG **** */ var config = {}; const storage = storageCreator(config); var controller = Botkit.slackbot({ interactive_replies: true, storage }); export { controller }; /** * User has joined slack channel ==> make connection * then onboard! */ controller.on('team_join', function (bot, message) { console.log("\n\n\n ~~ joined the team ~~ \n\n\n"); const SlackUserId = message.user.id; console.log(message.user.id); bot.api.users.info({ user: SlackUserId }, (err, response) => { if (!err) { const { user, user: { id, team_id, name, tz } } = response; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); }); /** * User has updated data ==> update our DB! */ controller.on('user_change', function (bot, message) { console.log("\n\n\n ~~ user updated profile ~~ \n\n\n"); if (message && message.user) { const { user, user: { name, id, team_id, tz } } = message; const SlackUserId = id; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); // simple way to keep track of bots export var bots = {}; if (!process.env.SLACK_ID || !process.env.SLACK_SECRET || !process.env.HTTP_PORT) { console.log('Error: Specify SLACK_ID SLACK_SECRET and HTTP_PORT in environment'); process.exit(1); } // Custom Toki Config export function customConfigBot(controller) { // beef up the bot setupReceiveMiddleware(controller); notWitController(controller); dashboardController(controller); pingsController(controller); sessionsController(controller); slashController(controller); miscController(controller); } // try to avoid repeat RTM's export function trackBot(bot) { bots[bot.config.token] = bot; } /** * *** TURN ON THE BOT **** * VIA SIGNUP OR LOGIN */
console.log(`\n\n\n\n CONNECTING ON INSTALL \n\n\n\n`); let bot = controller.spawn(team_config); controller.trigger('create_bot', [bot, team_config]); } export function connectOnLogin(identity) { // bot already exists, get bot token for this users team var SlackUserId = identity.user_id; var TeamId = identity.team_id; models.Team.find({ where: { TeamId } }) .then((team) => { const { token } = team; if (token) { var bot = controller.spawn({ token }); controller.trigger('login_bot', [bot, identity]); } }) } controller.on('rtm_open',function(bot) { console.log(`\n\n\n\n** The RTM api just connected! for bot token: ${bot.config.token}\n\n\n`); }); // upon install controller.on('create_bot', (bot,team) => { const { id, url, name, bot: { token, user_id, createdBy, accessToken, scopes } } = team; // this is what is used to save team data const teamConfig = { TeamId: id, createdBy, url, name, token, scopes, accessToken } if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! restarting bot due to re-install"); // restart the bot bots[bot.config.token].closeRTM(); } bot.startRTM((err) => { if (!err) { console.log("\n\n RTM on with team install and listening \n\n"); trackBot(bot); controller.saveTeam(teamConfig, (err, id) => { if (err) { console.log("Error saving team") } else { console.log("Team " + team.name + " saved"); console.log(`\n\n installing users... \n\n`); bot.api.users.list({}, (err, response) => { if (!err) { const { members } = response; seedAndUpdateUsers(members); } firstInstallInitiateConversation(bot, team); }); } }); } else { console.log("RTM failed") } }); }); // subsequent logins controller.on('login_bot', (bot,identity) => { if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! do nothing."); loginInitiateConversation(bot, identity); } else { bot.startRTM((err) => { if (!err) { console.log("RTM on and listening"); trackBot(bot); loginInitiateConversation(bot, identity); } else { console.log("RTM failed") console.log(err); } }); } });
export function connectOnInstall(team_config) {
random_line_split
index.js
import Botkit from 'botkit'; import os from 'os'; import Wit from 'botkit-middleware-witai'; import moment from 'moment-timezone'; import models from '../../app/models'; import storageCreator from '../lib/storage'; import setupReceiveMiddleware from '../middleware/receiveMiddleware'; import notWitController from './notWit'; import miscController from './misc'; import sessionsController from './sessions'; import pingsController from './pings'; import slashController from './slash'; import dashboardController from './dashboard'; import { seedAndUpdateUsers } from '../../app/scripts'; require('dotenv').config(); var env = process.env.NODE_ENV || 'development'; if (env == 'development') { process.env.SLACK_ID = process.env.DEV_SLACK_ID; process.env.SLACK_SECRET = process.env.DEV_SLACK_SECRET; } // actions import { firstInstallInitiateConversation, loginInitiateConversation } from '../actions'; // Wit Brain if (process.env.WIT_TOKEN) { var wit = Wit({ token: process.env.WIT_TOKEN, minimum_confidence: 0.55 }); } else { console.log('Error: Specify WIT_TOKEN in environment'); process.exit(1); } export { wit }; /** * *** CONFIG **** */ var config = {}; const storage = storageCreator(config); var controller = Botkit.slackbot({ interactive_replies: true, storage }); export { controller }; /** * User has joined slack channel ==> make connection * then onboard! */ controller.on('team_join', function (bot, message) { console.log("\n\n\n ~~ joined the team ~~ \n\n\n"); const SlackUserId = message.user.id; console.log(message.user.id); bot.api.users.info({ user: SlackUserId }, (err, response) => { if (!err) { const { user, user: { id, team_id, name, tz } } = response; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); }); /** * User has updated data ==> update our DB! */ controller.on('user_change', function (bot, message) { console.log("\n\n\n ~~ user updated profile ~~ \n\n\n"); if (message && message.user) { const { user, user: { name, id, team_id, tz } } = message; const SlackUserId = id; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); // simple way to keep track of bots export var bots = {}; if (!process.env.SLACK_ID || !process.env.SLACK_SECRET || !process.env.HTTP_PORT) { console.log('Error: Specify SLACK_ID SLACK_SECRET and HTTP_PORT in environment'); process.exit(1); } // Custom Toki Config export function customConfigBot(controller) { // beef up the bot setupReceiveMiddleware(controller); notWitController(controller); dashboardController(controller); pingsController(controller); sessionsController(controller); slashController(controller); miscController(controller); } // try to avoid repeat RTM's export function trackBot(bot) { bots[bot.config.token] = bot; } /** * *** TURN ON THE BOT **** * VIA SIGNUP OR LOGIN */ export function connectOnInstall(team_config) { console.log(`\n\n\n\n CONNECTING ON INSTALL \n\n\n\n`); let bot = controller.spawn(team_config); controller.trigger('create_bot', [bot, team_config]); } export function connectOnLogin(identity) { // bot already exists, get bot token for this users team var SlackUserId = identity.user_id; var TeamId = identity.team_id; models.Team.find({ where: { TeamId } }) .then((team) => { const { token } = team; if (token) { var bot = controller.spawn({ token }); controller.trigger('login_bot', [bot, identity]); } }) } controller.on('rtm_open',function(bot) { console.log(`\n\n\n\n** The RTM api just connected! for bot token: ${bot.config.token}\n\n\n`); }); // upon install controller.on('create_bot', (bot,team) => { const { id, url, name, bot: { token, user_id, createdBy, accessToken, scopes } } = team; // this is what is used to save team data const teamConfig = { TeamId: id, createdBy, url, name, token, scopes, accessToken } if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! restarting bot due to re-install"); // restart the bot bots[bot.config.token].closeRTM(); } bot.startRTM((err) => { if (!err) { console.log("\n\n RTM on with team install and listening \n\n"); trackBot(bot); controller.saveTeam(teamConfig, (err, id) => { if (err) { console.log("Error saving team") } else { console.log("Team " + team.name + " saved"); console.log(`\n\n installing users... \n\n`); bot.api.users.list({}, (err, response) => { if (!err) { const { members } = response; seedAndUpdateUsers(members); } firstInstallInitiateConversation(bot, team); }); } }); } else { console.log("RTM failed") } }); }); // subsequent logins controller.on('login_bot', (bot,identity) => { if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! do nothing."); loginInitiateConversation(bot, identity); } else { bot.startRTM((err) => { if (!err)
else { console.log("RTM failed") console.log(err); } }); } });
{ console.log("RTM on and listening"); trackBot(bot); loginInitiateConversation(bot, identity); }
conditional_block
__init__.py
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico 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. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from flask import session from werkzeug.exceptions import Forbidden from indico.modules.rb.controllers import RHRoomBookingBase from indico.modules.rb.util import rb_is_admin from indico.util.i18n import _ class RHRoomBookingAdminBase(RHRoomBookingBase): """ Adds admin authorization. All classes that implement admin tasks should be derived from this class. """ def _checkProtection(self): if session.user is None: self._checkSessionUser() elif not rb_is_admin(session.user):
raise Forbidden(_('You are not authorized to take this action.'))
conditional_block
__init__.py
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico 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. # # Indico is distributed in the hope that it will be useful, but
# along with Indico; if not, see <http://www.gnu.org/licenses/>. from flask import session from werkzeug.exceptions import Forbidden from indico.modules.rb.controllers import RHRoomBookingBase from indico.modules.rb.util import rb_is_admin from indico.util.i18n import _ class RHRoomBookingAdminBase(RHRoomBookingBase): """ Adds admin authorization. All classes that implement admin tasks should be derived from this class. """ def _checkProtection(self): if session.user is None: self._checkSessionUser() elif not rb_is_admin(session.user): raise Forbidden(_('You are not authorized to take this action.'))
# 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
random_line_split