file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
material.ts
import { Theme } from '../../themes/default'; import { StyleProps } from './default'; export const style = ({ theme, main, }: ThemedStyledProps<StyleProps, Theme>) => css` display: flex; flex: 0 0 1; padding-left: 1px; background-color: ${theme.base01}; width: 100%; overflow: hidden; ${!main && ` border-top: 1px solid ${theme.base01}; border-bottom: 1px solid ${theme.base02}; `} > div { display: flex; align-items: flex-end; flex-wrap: nowrap; button { background-color: ${theme.base01}; color: ${theme.base07}; min-height: 30px; padding: 0 2em; ${main && 'text-transform: uppercase;'} cursor: pointer; border: none; border-bottom: 2px solid transparent; text-align: center; overflow: hidden; outline: 0; transition: all 0.5s; &:hover, &:focus { border-bottom: 2px solid ${theme.base03}; color: ${theme.base04}; } &.collapsed { display: none; } ${ripple(theme)} } > [data-selected] { border-bottom: 2px solid ${theme.base0D}; } } > div:nth-child(2) { display: block; z-index: 10; button { display: block; background: ${theme.base00}; width: 100%; } } `;
import { css, ThemedStyledProps } from 'styled-components'; import { ripple } from '../../utils/animations';
random_line_split
constantOverloadFunctionNoSubtypeError.js
//// [constantOverloadFunctionNoSubtypeError.ts] class Base { foo() { } } class Derived1 extends Base { bar() { } } class Derived2 extends Base { baz() { } } class Derived3 extends Base { biz() { } } function foo(tagName: 'canvas'): Derived3; function foo(tagName: 'div'): Derived2; function foo(tagName: 'span'): Derived1; function foo(tagName: number): Base; function foo(tagName: any): Base { return null; } //// [constantOverloadFunctionNoSubtypeError.js]
var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Base = (function () { function Base() { } Base.prototype.foo = function () { }; return Base; })(); var Derived1 = (function (_super) { __extends(Derived1, _super); function Derived1() { _super.apply(this, arguments); } Derived1.prototype.bar = function () { }; return Derived1; })(Base); var Derived2 = (function (_super) { __extends(Derived2, _super); function Derived2() { _super.apply(this, arguments); } Derived2.prototype.baz = function () { }; return Derived2; })(Base); var Derived3 = (function (_super) { __extends(Derived3, _super); function Derived3() { _super.apply(this, arguments); } Derived3.prototype.biz = function () { }; return Derived3; })(Base); function foo(tagName) { return null; }
random_line_split
constantOverloadFunctionNoSubtypeError.js
//// [constantOverloadFunctionNoSubtypeError.ts] class Base { foo() { } } class Derived1 extends Base { bar() { } } class Derived2 extends Base { baz() { } } class Derived3 extends Base { biz() { } } function foo(tagName: 'canvas'): Derived3; function foo(tagName: 'div'): Derived2; function foo(tagName: 'span'): Derived1; function foo(tagName: number): Base; function foo(tagName: any): Base { return null; } //// [constantOverloadFunctionNoSubtypeError.js] var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function
() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Base = (function () { function Base() { } Base.prototype.foo = function () { }; return Base; })(); var Derived1 = (function (_super) { __extends(Derived1, _super); function Derived1() { _super.apply(this, arguments); } Derived1.prototype.bar = function () { }; return Derived1; })(Base); var Derived2 = (function (_super) { __extends(Derived2, _super); function Derived2() { _super.apply(this, arguments); } Derived2.prototype.baz = function () { }; return Derived2; })(Base); var Derived3 = (function (_super) { __extends(Derived3, _super); function Derived3() { _super.apply(this, arguments); } Derived3.prototype.biz = function () { }; return Derived3; })(Base); function foo(tagName) { return null; }
__
identifier_name
constantOverloadFunctionNoSubtypeError.js
//// [constantOverloadFunctionNoSubtypeError.ts] class Base { foo() { } } class Derived1 extends Base { bar() { } } class Derived2 extends Base { baz() { } } class Derived3 extends Base { biz()
} function foo(tagName: 'canvas'): Derived3; function foo(tagName: 'div'): Derived2; function foo(tagName: 'span'): Derived1; function foo(tagName: number): Base; function foo(tagName: any): Base { return null; } //// [constantOverloadFunctionNoSubtypeError.js] var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Base = (function () { function Base() { } Base.prototype.foo = function () { }; return Base; })(); var Derived1 = (function (_super) { __extends(Derived1, _super); function Derived1() { _super.apply(this, arguments); } Derived1.prototype.bar = function () { }; return Derived1; })(Base); var Derived2 = (function (_super) { __extends(Derived2, _super); function Derived2() { _super.apply(this, arguments); } Derived2.prototype.baz = function () { }; return Derived2; })(Base); var Derived3 = (function (_super) { __extends(Derived3, _super); function Derived3() { _super.apply(this, arguments); } Derived3.prototype.biz = function () { }; return Derived3; })(Base); function foo(tagName) { return null; }
{ }
identifier_body
nimbus_prod.py
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys from resource_management.libraries.script import Script from storm import storm from supervisord_service import supervisord_service, supervisord_check_status from resource_management.libraries.functions import conf_select from resource_management.libraries.functions import stack_select from resource_management.libraries.functions import format from resource_management.core.resources.system import Execute from resource_management.libraries.functions.stack_features import check_stack_feature from resource_management.libraries.functions import StackFeature class Nimbus(Script): def get_component_name(self): return "storm-nimbus" def install(self, env): self.install_packages(env) self.configure(env) def configure(self, env): import params env.set_params(params) storm() def pre_upgrade_restart(self, env, upgrade_type=None): import params env.set_params(params) if params.version and check_stack_feature(StackFeature.ROLLING_UPGRADE, params.version): conf_select.select(params.stack_name, "storm", params.version) stack_select.select("storm-client", params.version) stack_select.select("storm-nimbus", params.version) def start(self, env, upgrade_type=None): import params env.set_params(params) self.configure(env) supervisord_service("nimbus", action="start") def
(self, env, upgrade_type=None): import params env.set_params(params) supervisord_service("nimbus", action="stop") def status(self, env): supervisord_check_status("nimbus") def get_log_folder(self): import params return params.log_dir def get_user(self): import params return params.storm_user if __name__ == "__main__": Nimbus().execute()
stop
identifier_name
nimbus_prod.py
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys from resource_management.libraries.script import Script from storm import storm from supervisord_service import supervisord_service, supervisord_check_status from resource_management.libraries.functions import conf_select from resource_management.libraries.functions import stack_select from resource_management.libraries.functions import format from resource_management.core.resources.system import Execute from resource_management.libraries.functions.stack_features import check_stack_feature from resource_management.libraries.functions import StackFeature class Nimbus(Script): def get_component_name(self): return "storm-nimbus" def install(self, env): self.install_packages(env) self.configure(env) def configure(self, env): import params env.set_params(params) storm() def pre_upgrade_restart(self, env, upgrade_type=None):
def start(self, env, upgrade_type=None): import params env.set_params(params) self.configure(env) supervisord_service("nimbus", action="start") def stop(self, env, upgrade_type=None): import params env.set_params(params) supervisord_service("nimbus", action="stop") def status(self, env): supervisord_check_status("nimbus") def get_log_folder(self): import params return params.log_dir def get_user(self): import params return params.storm_user if __name__ == "__main__": Nimbus().execute()
import params env.set_params(params) if params.version and check_stack_feature(StackFeature.ROLLING_UPGRADE, params.version): conf_select.select(params.stack_name, "storm", params.version) stack_select.select("storm-client", params.version) stack_select.select("storm-nimbus", params.version)
identifier_body
nimbus_prod.py
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys from resource_management.libraries.script import Script from storm import storm from supervisord_service import supervisord_service, supervisord_check_status from resource_management.libraries.functions import conf_select from resource_management.libraries.functions import stack_select from resource_management.libraries.functions import format from resource_management.core.resources.system import Execute from resource_management.libraries.functions.stack_features import check_stack_feature from resource_management.libraries.functions import StackFeature class Nimbus(Script): def get_component_name(self): return "storm-nimbus" def install(self, env): self.install_packages(env) self.configure(env) def configure(self, env): import params env.set_params(params) storm() def pre_upgrade_restart(self, env, upgrade_type=None): import params env.set_params(params) if params.version and check_stack_feature(StackFeature.ROLLING_UPGRADE, params.version): conf_select.select(params.stack_name, "storm", params.version) stack_select.select("storm-client", params.version) stack_select.select("storm-nimbus", params.version) def start(self, env, upgrade_type=None): import params env.set_params(params) self.configure(env) supervisord_service("nimbus", action="start") def stop(self, env, upgrade_type=None): import params env.set_params(params) supervisord_service("nimbus", action="stop") def status(self, env): supervisord_check_status("nimbus") def get_log_folder(self): import params return params.log_dir def get_user(self): import params return params.storm_user if __name__ == "__main__":
Nimbus().execute()
conditional_block
nimbus_prod.py
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys from resource_management.libraries.script import Script from storm import storm from supervisord_service import supervisord_service, supervisord_check_status from resource_management.libraries.functions import conf_select from resource_management.libraries.functions import stack_select from resource_management.libraries.functions import format from resource_management.core.resources.system import Execute from resource_management.libraries.functions.stack_features import check_stack_feature from resource_management.libraries.functions import StackFeature class Nimbus(Script): def get_component_name(self): return "storm-nimbus" def install(self, env): self.install_packages(env) self.configure(env) def configure(self, env): import params env.set_params(params) storm() def pre_upgrade_restart(self, env, upgrade_type=None): import params
stack_select.select("storm-nimbus", params.version) def start(self, env, upgrade_type=None): import params env.set_params(params) self.configure(env) supervisord_service("nimbus", action="start") def stop(self, env, upgrade_type=None): import params env.set_params(params) supervisord_service("nimbus", action="stop") def status(self, env): supervisord_check_status("nimbus") def get_log_folder(self): import params return params.log_dir def get_user(self): import params return params.storm_user if __name__ == "__main__": Nimbus().execute()
env.set_params(params) if params.version and check_stack_feature(StackFeature.ROLLING_UPGRADE, params.version): conf_select.select(params.stack_name, "storm", params.version) stack_select.select("storm-client", params.version)
random_line_split
__init__.py
" TIME_TILL_UNAVAILABLE = timedelta(minutes=150) SERVICE_PLAY_RINGTONE = "play_ringtone" SERVICE_STOP_RINGTONE = "stop_ringtone" SERVICE_ADD_DEVICE = "add_device" SERVICE_REMOVE_DEVICE = "remove_device" SERVICE_SCHEMA_PLAY_RINGTONE = vol.Schema( { vol.Required(ATTR_RINGTONE_ID): vol.All( vol.Coerce(int), vol.NotIn([9, 14, 15, 16, 17, 18, 19]) ), vol.Optional(ATTR_RINGTONE_VOL): vol.All( vol.Coerce(int), vol.Clamp(min=0, max=100) ), } ) SERVICE_SCHEMA_REMOVE_DEVICE = vol.Schema( {vol.Required(ATTR_DEVICE_ID): vol.All(cv.string, vol.Length(min=14, max=14))} ) def setup(hass, config): """Set up the Xiaomi component.""" def play_ringtone_service(call): """Service to play ringtone through Gateway.""" ring_id = call.data.get(ATTR_RINGTONE_ID) gateway = call.data.get(ATTR_GW_MAC) kwargs = {"mid": ring_id} ring_vol = call.data.get(ATTR_RINGTONE_VOL) if ring_vol is not None: kwargs["vol"] = ring_vol gateway.write_to_hub(gateway.sid, **kwargs) def stop_ringtone_service(call): """Service to stop playing ringtone on Gateway.""" gateway = call.data.get(ATTR_GW_MAC) gateway.write_to_hub(gateway.sid, mid=10000) def add_device_service(call): """Service to add a new sub-device within the next 30 seconds.""" gateway = call.data.get(ATTR_GW_MAC) gateway.write_to_hub(gateway.sid, join_permission="yes") hass.components.persistent_notification.async_create( "Join permission enabled for 30 seconds! " "Please press the pairing button of the new device once.", title="Xiaomi Aqara Gateway", ) def remove_device_service(call): """Service to remove a sub-device from the gateway.""" device_id = call.data.get(ATTR_DEVICE_ID) gateway = call.data.get(ATTR_GW_MAC) gateway.write_to_hub(gateway.sid, remove_device=device_id) gateway_only_schema = _add_gateway_to_schema(hass, vol.Schema({})) hass.services.register( DOMAIN, SERVICE_PLAY_RINGTONE, play_ringtone_service, schema=_add_gateway_to_schema(hass, SERVICE_SCHEMA_PLAY_RINGTONE), ) hass.services.register( DOMAIN, SERVICE_STOP_RINGTONE, stop_ringtone_service, schema=gateway_only_schema ) hass.services.register( DOMAIN, SERVICE_ADD_DEVICE, add_device_service, schema=gateway_only_schema ) hass.services.register( DOMAIN, SERVICE_REMOVE_DEVICE, remove_device_service, schema=_add_gateway_to_schema(hass, SERVICE_SCHEMA_REMOVE_DEVICE), ) return True async def async_setup_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Set up the xiaomi aqara components from a config entry.""" hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN].setdefault(GATEWAYS_KEY, {}) # Connect to Xiaomi Aqara Gateway xiaomi_gateway = await hass.async_add_executor_job( XiaomiGateway, entry.data[CONF_HOST], entry.data[CONF_SID], entry.data[CONF_KEY], DEFAULT_DISCOVERY_RETRY, entry.data[CONF_INTERFACE], entry.data[CONF_PORT], entry.data[CONF_PROTOCOL], ) hass.data[DOMAIN][GATEWAYS_KEY][entry.entry_id] = xiaomi_gateway gateway_discovery = hass.data[DOMAIN].setdefault( LISTENER_KEY, XiaomiGatewayDiscovery(hass.add_job, [], entry.data[CONF_INTERFACE]), ) if len(hass.data[DOMAIN][GATEWAYS_KEY]) == 1: # start listining for local pushes (only once) await hass.async_add_executor_job(gateway_discovery.listen) # register stop callback to shutdown listining for local pushes def
(event): """Stop Xiaomi Socket.""" _LOGGER.debug("Shutting down Xiaomi Gateway Listener") gateway_discovery.stop_listen() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_xiaomi) gateway_discovery.gateways[entry.data[CONF_HOST]] = xiaomi_gateway _LOGGER.debug( "Gateway with host '%s' connected, listening for broadcasts", entry.data[CONF_HOST], ) device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, identifiers={(DOMAIN, entry.unique_id)}, manufacturer="Xiaomi Aqara", name=entry.title, sw_version=entry.data[CONF_PROTOCOL], ) if entry.data[CONF_KEY] is not None: platforms = GATEWAY_PLATFORMS else: platforms = GATEWAY_PLATFORMS_NO_KEY hass.config_entries.async_setup_platforms(entry, platforms) return True async def async_unload_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Unload a config entry.""" if entry.data[CONF_KEY] is not None: platforms = GATEWAY_PLATFORMS else: platforms = GATEWAY_PLATFORMS_NO_KEY unload_ok = await hass.config_entries.async_unload_platforms(entry, platforms) if unload_ok: hass.data[DOMAIN][GATEWAYS_KEY].pop(entry.entry_id) if len(hass.data[DOMAIN][GATEWAYS_KEY]) == 0: # No gateways left, stop Xiaomi socket hass.data[DOMAIN].pop(GATEWAYS_KEY) _LOGGER.debug("Shutting down Xiaomi Gateway Listener") gateway_discovery = hass.data[DOMAIN].pop(LISTENER_KEY) await hass.async_add_executor_job(gateway_discovery.stop_listen) return unload_ok class XiaomiDevice(Entity): """Representation a base Xiaomi device.""" def __init__(self, device, device_type, xiaomi_hub, config_entry): """Initialize the Xiaomi device.""" self._state = None self._is_available = True self._sid = device["sid"] self._model = device["model"] self._protocol = device["proto"] self._name = f"{device_type}_{self._sid}" self._device_name = f"{self._model}_{self._sid}" self._type = device_type self._write_to_hub = xiaomi_hub.write_to_hub self._get_from_hub = xiaomi_hub.get_from_hub self._extra_state_attributes = {} self._remove_unavailability_tracker = None self._xiaomi_hub = xiaomi_hub self.parse_data(device["data"], device["raw_data"]) self.parse_voltage(device["data"]) if hasattr(self, "_data_key") and self._data_key: # pylint: disable=no-member self._unique_id = ( f"{self._data_key}{self._sid}" # pylint: disable=no-member ) else: self._unique_id = f"{self._type}{self._sid}" self._gateway_id = config_entry.unique_id if config_entry.data[CONF_MAC] == format_mac(self._sid): # this entity belongs to the gateway itself self._is_gateway = True self._device_id = config_entry.unique_id else: # this entity is connected through zigbee self._is_gateway = False self._device_id = self._sid def _add_push_data_job(self, *args): self.hass.add_job(self.push_data, *args) async def async_added_to_hass(self): """Start unavailability tracking.""" self._xiaomi_hub.callbacks[self._sid].append(self._add_push_data_job) self._async_track_unavailable() @property def name(self): """Return the name of the device.""" return self._name @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def device_id(self): """Return the device id of the Xiaomi Aqara device.""" return self._device_id @property def device_info(self): """Return the device info of the Xiaomi Aqara device.""" if self._is_gateway: device_info = { "identifiers": {(DOMAIN, self._device_id)}, "model": self._model, } else: device_info = { "connections": {(dr.CONNECTION_ZIGBEE, self._device_id)}, "identifiers": {(DOMAIN, self._device_id)}, "manufacturer": "Xiaomi Aqara", "model": self._model, "name": self._device_name, "sw_version": self._protocol, "via_device": (DOMAIN, self._gateway_id), } return device_info @property def available(self): """Return True if entity is available.""" return self._is_available @property def should_poll(self): """Return the polling state. No polling needed.""" return False @property def extra_state_attributes(self): """Return the state attributes.""" return self._extra_state_attributes @
stop_xiaomi
identifier_name
__init__.py
_SCHEMA_PLAY_RINGTONE), ) hass.services.register( DOMAIN, SERVICE_STOP_RINGTONE, stop_ringtone_service, schema=gateway_only_schema ) hass.services.register( DOMAIN, SERVICE_ADD_DEVICE, add_device_service, schema=gateway_only_schema ) hass.services.register( DOMAIN, SERVICE_REMOVE_DEVICE, remove_device_service, schema=_add_gateway_to_schema(hass, SERVICE_SCHEMA_REMOVE_DEVICE), ) return True async def async_setup_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Set up the xiaomi aqara components from a config entry.""" hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN].setdefault(GATEWAYS_KEY, {}) # Connect to Xiaomi Aqara Gateway xiaomi_gateway = await hass.async_add_executor_job( XiaomiGateway, entry.data[CONF_HOST], entry.data[CONF_SID], entry.data[CONF_KEY], DEFAULT_DISCOVERY_RETRY, entry.data[CONF_INTERFACE], entry.data[CONF_PORT], entry.data[CONF_PROTOCOL], ) hass.data[DOMAIN][GATEWAYS_KEY][entry.entry_id] = xiaomi_gateway gateway_discovery = hass.data[DOMAIN].setdefault( LISTENER_KEY, XiaomiGatewayDiscovery(hass.add_job, [], entry.data[CONF_INTERFACE]), ) if len(hass.data[DOMAIN][GATEWAYS_KEY]) == 1: # start listining for local pushes (only once) await hass.async_add_executor_job(gateway_discovery.listen) # register stop callback to shutdown listining for local pushes def stop_xiaomi(event): """Stop Xiaomi Socket.""" _LOGGER.debug("Shutting down Xiaomi Gateway Listener") gateway_discovery.stop_listen() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_xiaomi) gateway_discovery.gateways[entry.data[CONF_HOST]] = xiaomi_gateway _LOGGER.debug( "Gateway with host '%s' connected, listening for broadcasts", entry.data[CONF_HOST], ) device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, identifiers={(DOMAIN, entry.unique_id)}, manufacturer="Xiaomi Aqara", name=entry.title, sw_version=entry.data[CONF_PROTOCOL], ) if entry.data[CONF_KEY] is not None: platforms = GATEWAY_PLATFORMS else: platforms = GATEWAY_PLATFORMS_NO_KEY hass.config_entries.async_setup_platforms(entry, platforms) return True async def async_unload_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Unload a config entry.""" if entry.data[CONF_KEY] is not None: platforms = GATEWAY_PLATFORMS else: platforms = GATEWAY_PLATFORMS_NO_KEY unload_ok = await hass.config_entries.async_unload_platforms(entry, platforms) if unload_ok: hass.data[DOMAIN][GATEWAYS_KEY].pop(entry.entry_id) if len(hass.data[DOMAIN][GATEWAYS_KEY]) == 0: # No gateways left, stop Xiaomi socket hass.data[DOMAIN].pop(GATEWAYS_KEY) _LOGGER.debug("Shutting down Xiaomi Gateway Listener") gateway_discovery = hass.data[DOMAIN].pop(LISTENER_KEY) await hass.async_add_executor_job(gateway_discovery.stop_listen) return unload_ok class XiaomiDevice(Entity): """Representation a base Xiaomi device.""" def __init__(self, device, device_type, xiaomi_hub, config_entry): """Initialize the Xiaomi device.""" self._state = None self._is_available = True self._sid = device["sid"] self._model = device["model"] self._protocol = device["proto"] self._name = f"{device_type}_{self._sid}" self._device_name = f"{self._model}_{self._sid}" self._type = device_type self._write_to_hub = xiaomi_hub.write_to_hub self._get_from_hub = xiaomi_hub.get_from_hub self._extra_state_attributes = {} self._remove_unavailability_tracker = None self._xiaomi_hub = xiaomi_hub self.parse_data(device["data"], device["raw_data"]) self.parse_voltage(device["data"]) if hasattr(self, "_data_key") and self._data_key: # pylint: disable=no-member self._unique_id = ( f"{self._data_key}{self._sid}" # pylint: disable=no-member ) else: self._unique_id = f"{self._type}{self._sid}" self._gateway_id = config_entry.unique_id if config_entry.data[CONF_MAC] == format_mac(self._sid): # this entity belongs to the gateway itself self._is_gateway = True self._device_id = config_entry.unique_id else: # this entity is connected through zigbee self._is_gateway = False self._device_id = self._sid def _add_push_data_job(self, *args): self.hass.add_job(self.push_data, *args) async def async_added_to_hass(self): """Start unavailability tracking.""" self._xiaomi_hub.callbacks[self._sid].append(self._add_push_data_job) self._async_track_unavailable() @property def name(self): """Return the name of the device.""" return self._name @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def device_id(self): """Return the device id of the Xiaomi Aqara device.""" return self._device_id @property def device_info(self): """Return the device info of the Xiaomi Aqara device.""" if self._is_gateway: device_info = { "identifiers": {(DOMAIN, self._device_id)}, "model": self._model, } else: device_info = { "connections": {(dr.CONNECTION_ZIGBEE, self._device_id)}, "identifiers": {(DOMAIN, self._device_id)}, "manufacturer": "Xiaomi Aqara", "model": self._model, "name": self._device_name, "sw_version": self._protocol, "via_device": (DOMAIN, self._gateway_id), } return device_info @property def available(self): """Return True if entity is available.""" return self._is_available @property def should_poll(self): """Return the polling state. No polling needed.""" return False @property def extra_state_attributes(self): """Return the state attributes.""" return self._extra_state_attributes @callback def _async_set_unavailable(self, now): """Set state to UNAVAILABLE.""" self._remove_unavailability_tracker = None self._is_available = False self.async_write_ha_state() @callback def _async_track_unavailable(self): if self._remove_unavailability_tracker: self._remove_unavailability_tracker() self._remove_unavailability_tracker = async_track_point_in_utc_time( self.hass, self._async_set_unavailable, utcnow() + TIME_TILL_UNAVAILABLE ) if not self._is_available: self._is_available = True return True return False @callback def push_data(self, data, raw_data): """Push from Hub.""" _LOGGER.debug("PUSH >> %s: %s", self, data) was_unavailable = self._async_track_unavailable() is_data = self.parse_data(data, raw_data) is_voltage = self.parse_voltage(data) if is_data or is_voltage or was_unavailable: self.async_write_ha_state() def parse_voltage(self, data): """Parse battery level data sent by gateway.""" if "voltage" in data: voltage_key = "voltage" elif "battery_voltage" in data: voltage_key = "battery_voltage" else: return False max_volt = 3300 min_volt = 2800 voltage = data[voltage_key] self._extra_state_attributes[ATTR_VOLTAGE] = round(voltage / 1000.0, 2) voltage = min(voltage, max_volt) voltage = max(voltage, min_volt) percent = ((voltage - min_volt) / (max_volt - min_volt)) * 100 self._extra_state_attributes[ATTR_BATTERY_LEVEL] = round(percent, 1) return True def parse_data(self, data, raw_data): """Parse data sent by gateway.""" raise NotImplementedError() def _add_gateway_to_schema(hass, schema): """Extend a voluptuous schema with a gateway validator.""" def gateway(sid): """Convert sid to a gateway.""" sid = str(sid).replace(":", "").lower() for gateway in hass.data[DOMAIN][GATEWAYS_KEY].values(): if gateway.sid == sid: return gateway raise vol.Invalid(f"Unknown gateway sid {sid}")
kwargs = {} xiaomi_data = hass.data.get(DOMAIN)
random_line_split
__init__.py
" TIME_TILL_UNAVAILABLE = timedelta(minutes=150) SERVICE_PLAY_RINGTONE = "play_ringtone" SERVICE_STOP_RINGTONE = "stop_ringtone" SERVICE_ADD_DEVICE = "add_device" SERVICE_REMOVE_DEVICE = "remove_device" SERVICE_SCHEMA_PLAY_RINGTONE = vol.Schema( { vol.Required(ATTR_RINGTONE_ID): vol.All( vol.Coerce(int), vol.NotIn([9, 14, 15, 16, 17, 18, 19]) ), vol.Optional(ATTR_RINGTONE_VOL): vol.All( vol.Coerce(int), vol.Clamp(min=0, max=100) ), } ) SERVICE_SCHEMA_REMOVE_DEVICE = vol.Schema( {vol.Required(ATTR_DEVICE_ID): vol.All(cv.string, vol.Length(min=14, max=14))} ) def setup(hass, config): """Set up the Xiaomi component.""" def play_ringtone_service(call):
def stop_ringtone_service(call): """Service to stop playing ringtone on Gateway.""" gateway = call.data.get(ATTR_GW_MAC) gateway.write_to_hub(gateway.sid, mid=10000) def add_device_service(call): """Service to add a new sub-device within the next 30 seconds.""" gateway = call.data.get(ATTR_GW_MAC) gateway.write_to_hub(gateway.sid, join_permission="yes") hass.components.persistent_notification.async_create( "Join permission enabled for 30 seconds! " "Please press the pairing button of the new device once.", title="Xiaomi Aqara Gateway", ) def remove_device_service(call): """Service to remove a sub-device from the gateway.""" device_id = call.data.get(ATTR_DEVICE_ID) gateway = call.data.get(ATTR_GW_MAC) gateway.write_to_hub(gateway.sid, remove_device=device_id) gateway_only_schema = _add_gateway_to_schema(hass, vol.Schema({})) hass.services.register( DOMAIN, SERVICE_PLAY_RINGTONE, play_ringtone_service, schema=_add_gateway_to_schema(hass, SERVICE_SCHEMA_PLAY_RINGTONE), ) hass.services.register( DOMAIN, SERVICE_STOP_RINGTONE, stop_ringtone_service, schema=gateway_only_schema ) hass.services.register( DOMAIN, SERVICE_ADD_DEVICE, add_device_service, schema=gateway_only_schema ) hass.services.register( DOMAIN, SERVICE_REMOVE_DEVICE, remove_device_service, schema=_add_gateway_to_schema(hass, SERVICE_SCHEMA_REMOVE_DEVICE), ) return True async def async_setup_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Set up the xiaomi aqara components from a config entry.""" hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN].setdefault(GATEWAYS_KEY, {}) # Connect to Xiaomi Aqara Gateway xiaomi_gateway = await hass.async_add_executor_job( XiaomiGateway, entry.data[CONF_HOST], entry.data[CONF_SID], entry.data[CONF_KEY], DEFAULT_DISCOVERY_RETRY, entry.data[CONF_INTERFACE], entry.data[CONF_PORT], entry.data[CONF_PROTOCOL], ) hass.data[DOMAIN][GATEWAYS_KEY][entry.entry_id] = xiaomi_gateway gateway_discovery = hass.data[DOMAIN].setdefault( LISTENER_KEY, XiaomiGatewayDiscovery(hass.add_job, [], entry.data[CONF_INTERFACE]), ) if len(hass.data[DOMAIN][GATEWAYS_KEY]) == 1: # start listining for local pushes (only once) await hass.async_add_executor_job(gateway_discovery.listen) # register stop callback to shutdown listining for local pushes def stop_xiaomi(event): """Stop Xiaomi Socket.""" _LOGGER.debug("Shutting down Xiaomi Gateway Listener") gateway_discovery.stop_listen() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_xiaomi) gateway_discovery.gateways[entry.data[CONF_HOST]] = xiaomi_gateway _LOGGER.debug( "Gateway with host '%s' connected, listening for broadcasts", entry.data[CONF_HOST], ) device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, identifiers={(DOMAIN, entry.unique_id)}, manufacturer="Xiaomi Aqara", name=entry.title, sw_version=entry.data[CONF_PROTOCOL], ) if entry.data[CONF_KEY] is not None: platforms = GATEWAY_PLATFORMS else: platforms = GATEWAY_PLATFORMS_NO_KEY hass.config_entries.async_setup_platforms(entry, platforms) return True async def async_unload_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Unload a config entry.""" if entry.data[CONF_KEY] is not None: platforms = GATEWAY_PLATFORMS else: platforms = GATEWAY_PLATFORMS_NO_KEY unload_ok = await hass.config_entries.async_unload_platforms(entry, platforms) if unload_ok: hass.data[DOMAIN][GATEWAYS_KEY].pop(entry.entry_id) if len(hass.data[DOMAIN][GATEWAYS_KEY]) == 0: # No gateways left, stop Xiaomi socket hass.data[DOMAIN].pop(GATEWAYS_KEY) _LOGGER.debug("Shutting down Xiaomi Gateway Listener") gateway_discovery = hass.data[DOMAIN].pop(LISTENER_KEY) await hass.async_add_executor_job(gateway_discovery.stop_listen) return unload_ok class XiaomiDevice(Entity): """Representation a base Xiaomi device.""" def __init__(self, device, device_type, xiaomi_hub, config_entry): """Initialize the Xiaomi device.""" self._state = None self._is_available = True self._sid = device["sid"] self._model = device["model"] self._protocol = device["proto"] self._name = f"{device_type}_{self._sid}" self._device_name = f"{self._model}_{self._sid}" self._type = device_type self._write_to_hub = xiaomi_hub.write_to_hub self._get_from_hub = xiaomi_hub.get_from_hub self._extra_state_attributes = {} self._remove_unavailability_tracker = None self._xiaomi_hub = xiaomi_hub self.parse_data(device["data"], device["raw_data"]) self.parse_voltage(device["data"]) if hasattr(self, "_data_key") and self._data_key: # pylint: disable=no-member self._unique_id = ( f"{self._data_key}{self._sid}" # pylint: disable=no-member ) else: self._unique_id = f"{self._type}{self._sid}" self._gateway_id = config_entry.unique_id if config_entry.data[CONF_MAC] == format_mac(self._sid): # this entity belongs to the gateway itself self._is_gateway = True self._device_id = config_entry.unique_id else: # this entity is connected through zigbee self._is_gateway = False self._device_id = self._sid def _add_push_data_job(self, *args): self.hass.add_job(self.push_data, *args) async def async_added_to_hass(self): """Start unavailability tracking.""" self._xiaomi_hub.callbacks[self._sid].append(self._add_push_data_job) self._async_track_unavailable() @property def name(self): """Return the name of the device.""" return self._name @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def device_id(self): """Return the device id of the Xiaomi Aqara device.""" return self._device_id @property def device_info(self): """Return the device info of the Xiaomi Aqara device.""" if self._is_gateway: device_info = { "identifiers": {(DOMAIN, self._device_id)}, "model": self._model, } else: device_info = { "connections": {(dr.CONNECTION_ZIGBEE, self._device_id)}, "identifiers": {(DOMAIN, self._device_id)}, "manufacturer": "Xiaomi Aqara", "model": self._model, "name": self._device_name, "sw_version": self._protocol, "via_device": (DOMAIN, self._gateway_id), } return device_info @property def available(self): """Return True if entity is available.""" return self._is_available @property def should_poll(self): """Return the polling state. No polling needed.""" return False @property def extra_state_attributes(self): """Return the state attributes.""" return self._extra_state_attributes @
"""Service to play ringtone through Gateway.""" ring_id = call.data.get(ATTR_RINGTONE_ID) gateway = call.data.get(ATTR_GW_MAC) kwargs = {"mid": ring_id} ring_vol = call.data.get(ATTR_RINGTONE_VOL) if ring_vol is not None: kwargs["vol"] = ring_vol gateway.write_to_hub(gateway.sid, **kwargs)
identifier_body
__init__.py
hass.services.register( DOMAIN, SERVICE_PLAY_RINGTONE, play_ringtone_service, schema=_add_gateway_to_schema(hass, SERVICE_SCHEMA_PLAY_RINGTONE), ) hass.services.register( DOMAIN, SERVICE_STOP_RINGTONE, stop_ringtone_service, schema=gateway_only_schema ) hass.services.register( DOMAIN, SERVICE_ADD_DEVICE, add_device_service, schema=gateway_only_schema ) hass.services.register( DOMAIN, SERVICE_REMOVE_DEVICE, remove_device_service, schema=_add_gateway_to_schema(hass, SERVICE_SCHEMA_REMOVE_DEVICE), ) return True async def async_setup_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Set up the xiaomi aqara components from a config entry.""" hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN].setdefault(GATEWAYS_KEY, {}) # Connect to Xiaomi Aqara Gateway xiaomi_gateway = await hass.async_add_executor_job( XiaomiGateway, entry.data[CONF_HOST], entry.data[CONF_SID], entry.data[CONF_KEY], DEFAULT_DISCOVERY_RETRY, entry.data[CONF_INTERFACE], entry.data[CONF_PORT], entry.data[CONF_PROTOCOL], ) hass.data[DOMAIN][GATEWAYS_KEY][entry.entry_id] = xiaomi_gateway gateway_discovery = hass.data[DOMAIN].setdefault( LISTENER_KEY, XiaomiGatewayDiscovery(hass.add_job, [], entry.data[CONF_INTERFACE]), ) if len(hass.data[DOMAIN][GATEWAYS_KEY]) == 1: # start listining for local pushes (only once) await hass.async_add_executor_job(gateway_discovery.listen) # register stop callback to shutdown listining for local pushes def stop_xiaomi(event): """Stop Xiaomi Socket.""" _LOGGER.debug("Shutting down Xiaomi Gateway Listener") gateway_discovery.stop_listen() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_xiaomi) gateway_discovery.gateways[entry.data[CONF_HOST]] = xiaomi_gateway _LOGGER.debug( "Gateway with host '%s' connected, listening for broadcasts", entry.data[CONF_HOST], ) device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, identifiers={(DOMAIN, entry.unique_id)}, manufacturer="Xiaomi Aqara", name=entry.title, sw_version=entry.data[CONF_PROTOCOL], ) if entry.data[CONF_KEY] is not None: platforms = GATEWAY_PLATFORMS else: platforms = GATEWAY_PLATFORMS_NO_KEY hass.config_entries.async_setup_platforms(entry, platforms) return True async def async_unload_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Unload a config entry.""" if entry.data[CONF_KEY] is not None: platforms = GATEWAY_PLATFORMS else: platforms = GATEWAY_PLATFORMS_NO_KEY unload_ok = await hass.config_entries.async_unload_platforms(entry, platforms) if unload_ok: hass.data[DOMAIN][GATEWAYS_KEY].pop(entry.entry_id) if len(hass.data[DOMAIN][GATEWAYS_KEY]) == 0: # No gateways left, stop Xiaomi socket hass.data[DOMAIN].pop(GATEWAYS_KEY) _LOGGER.debug("Shutting down Xiaomi Gateway Listener") gateway_discovery = hass.data[DOMAIN].pop(LISTENER_KEY) await hass.async_add_executor_job(gateway_discovery.stop_listen) return unload_ok class XiaomiDevice(Entity): """Representation a base Xiaomi device.""" def __init__(self, device, device_type, xiaomi_hub, config_entry): """Initialize the Xiaomi device.""" self._state = None self._is_available = True self._sid = device["sid"] self._model = device["model"] self._protocol = device["proto"] self._name = f"{device_type}_{self._sid}" self._device_name = f"{self._model}_{self._sid}" self._type = device_type self._write_to_hub = xiaomi_hub.write_to_hub self._get_from_hub = xiaomi_hub.get_from_hub self._extra_state_attributes = {} self._remove_unavailability_tracker = None self._xiaomi_hub = xiaomi_hub self.parse_data(device["data"], device["raw_data"]) self.parse_voltage(device["data"]) if hasattr(self, "_data_key") and self._data_key: # pylint: disable=no-member self._unique_id = ( f"{self._data_key}{self._sid}" # pylint: disable=no-member ) else: self._unique_id = f"{self._type}{self._sid}" self._gateway_id = config_entry.unique_id if config_entry.data[CONF_MAC] == format_mac(self._sid): # this entity belongs to the gateway itself self._is_gateway = True self._device_id = config_entry.unique_id else: # this entity is connected through zigbee self._is_gateway = False self._device_id = self._sid def _add_push_data_job(self, *args): self.hass.add_job(self.push_data, *args) async def async_added_to_hass(self): """Start unavailability tracking.""" self._xiaomi_hub.callbacks[self._sid].append(self._add_push_data_job) self._async_track_unavailable() @property def name(self): """Return the name of the device.""" return self._name @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def device_id(self): """Return the device id of the Xiaomi Aqara device.""" return self._device_id @property def device_info(self): """Return the device info of the Xiaomi Aqara device.""" if self._is_gateway: device_info = { "identifiers": {(DOMAIN, self._device_id)}, "model": self._model, } else: device_info = { "connections": {(dr.CONNECTION_ZIGBEE, self._device_id)}, "identifiers": {(DOMAIN, self._device_id)}, "manufacturer": "Xiaomi Aqara", "model": self._model, "name": self._device_name, "sw_version": self._protocol, "via_device": (DOMAIN, self._gateway_id), } return device_info @property def available(self): """Return True if entity is available.""" return self._is_available @property def should_poll(self): """Return the polling state. No polling needed.""" return False @property def extra_state_attributes(self): """Return the state attributes.""" return self._extra_state_attributes @callback def _async_set_unavailable(self, now): """Set state to UNAVAILABLE.""" self._remove_unavailability_tracker = None self._is_available = False self.async_write_ha_state() @callback def _async_track_unavailable(self): if self._remove_unavailability_tracker: self._remove_unavailability_tracker() self._remove_unavailability_tracker = async_track_point_in_utc_time( self.hass, self._async_set_unavailable, utcnow() + TIME_TILL_UNAVAILABLE ) if not self._is_available: self._is_available = True return True return False @callback def push_data(self, data, raw_data): """Push from Hub.""" _LOGGER.debug("PUSH >> %s: %s", self, data) was_unavailable = self._async_track_unavailable() is_data = self.parse_data(data, raw_data) is_voltage = self.parse_voltage(data) if is_data or is_voltage or was_unavailable: self.async_write_ha_state() def parse_voltage(self, data): """Parse battery level data sent by gateway.""" if "voltage" in data: voltage_key = "voltage" elif "battery_voltage" in data: voltage_key = "battery_voltage" else: return False max_volt = 3300 min_volt = 2800 voltage = data[voltage_key] self._extra_state_attributes[ATTR_VOLTAGE] = round(voltage / 1000.0, 2) voltage = min(voltage, max_volt) voltage = max(voltage, min_volt) percent = ((voltage - min_volt) / (max_volt - min_volt)) * 100 self._extra_state_attributes[ATTR_BATTERY_LEVEL] = round(percent, 1) return True def parse_data(self, data, raw_data): """Parse data sent by gateway.""" raise NotImplementedError() def _add_gateway_to_schema(hass, schema): """Extend a voluptuous schema with a gateway validator.""" def gateway(sid): """Convert sid to a gateway.""" sid = str(sid).replace(":", "").lower() for gateway in hass.data[DOMAIN][GATEWAYS_KEY].values():
if gateway.sid == sid: return gateway
conditional_block
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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
* 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. */ // TypeScript Version: 2.0 /** * Boolean indicating if the current environment is a touch device. * * @example * var bool = IS_TOUCH_DEVICE; * // returns <boolean> */ declare const IS_TOUCH_DEVICE: boolean; // EXPORTS // export = IS_TOUCH_DEVICE;
* distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
views.py
from django.shortcuts import render # Create your views here. from .models import Course, Student, StudentCourse from .serializers import CourseSerializer, StudentSerialiser from rest_framework import viewsets from rest_framework.decorators import detail_route, list_route from rest_framework.response import Response class StudentViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerialiser @list_route(methods=['GET']) def make(self, request): username = request.GET.get('username', None) if username:
return Response({'success': True}) class CourseViewSet(viewsets.ModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer def get_queryset(self): result = super(CourseViewSet, self).get_queryset() username = self.request.GET.get('username', None) active = self.request.GET.get('active', None) if not username or active != '1': return result user = Student.objects.get(nickname=username) courses_ids = StudentCourse.objects.filter(student=user, active=True).values_list('course_id', flat=True) return result.filter(id__in=courses_ids) @detail_route(methods=['GET']) def start(self, request, pk=None): username = request.GET.get('username', None) user = Student.objects.get(nickname=username) course = Course.objects.get(id=pk) student_course, created = StudentCourse.objects.get_or_create(student=user, course=course) StudentCourse.objects.filter(student=user).update(active=False) student_course.active = True student_course.save() return Response({'success': True})
Student.objects.get_or_create(nickname=username)
conditional_block
views.py
from django.shortcuts import render # Create your views here. from .models import Course, Student, StudentCourse from .serializers import CourseSerializer, StudentSerialiser from rest_framework import viewsets from rest_framework.decorators import detail_route, list_route from rest_framework.response import Response class StudentViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerialiser @list_route(methods=['GET']) def make(self, request): username = request.GET.get('username', None) if username: Student.objects.get_or_create(nickname=username) return Response({'success': True}) class CourseViewSet(viewsets.ModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer def get_queryset(self): result = super(CourseViewSet, self).get_queryset() username = self.request.GET.get('username', None) active = self.request.GET.get('active', None) if not username or active != '1': return result user = Student.objects.get(nickname=username) courses_ids = StudentCourse.objects.filter(student=user, active=True).values_list('course_id', flat=True) return result.filter(id__in=courses_ids) @detail_route(methods=['GET']) def
(self, request, pk=None): username = request.GET.get('username', None) user = Student.objects.get(nickname=username) course = Course.objects.get(id=pk) student_course, created = StudentCourse.objects.get_or_create(student=user, course=course) StudentCourse.objects.filter(student=user).update(active=False) student_course.active = True student_course.save() return Response({'success': True})
start
identifier_name
views.py
from django.shortcuts import render
from .serializers import CourseSerializer, StudentSerialiser from rest_framework import viewsets from rest_framework.decorators import detail_route, list_route from rest_framework.response import Response class StudentViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerialiser @list_route(methods=['GET']) def make(self, request): username = request.GET.get('username', None) if username: Student.objects.get_or_create(nickname=username) return Response({'success': True}) class CourseViewSet(viewsets.ModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer def get_queryset(self): result = super(CourseViewSet, self).get_queryset() username = self.request.GET.get('username', None) active = self.request.GET.get('active', None) if not username or active != '1': return result user = Student.objects.get(nickname=username) courses_ids = StudentCourse.objects.filter(student=user, active=True).values_list('course_id', flat=True) return result.filter(id__in=courses_ids) @detail_route(methods=['GET']) def start(self, request, pk=None): username = request.GET.get('username', None) user = Student.objects.get(nickname=username) course = Course.objects.get(id=pk) student_course, created = StudentCourse.objects.get_or_create(student=user, course=course) StudentCourse.objects.filter(student=user).update(active=False) student_course.active = True student_course.save() return Response({'success': True})
# Create your views here. from .models import Course, Student, StudentCourse
random_line_split
views.py
from django.shortcuts import render # Create your views here. from .models import Course, Student, StudentCourse from .serializers import CourseSerializer, StudentSerialiser from rest_framework import viewsets from rest_framework.decorators import detail_route, list_route from rest_framework.response import Response class StudentViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerialiser @list_route(methods=['GET']) def make(self, request): username = request.GET.get('username', None) if username: Student.objects.get_or_create(nickname=username) return Response({'success': True}) class CourseViewSet(viewsets.ModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer def get_queryset(self): result = super(CourseViewSet, self).get_queryset() username = self.request.GET.get('username', None) active = self.request.GET.get('active', None) if not username or active != '1': return result user = Student.objects.get(nickname=username) courses_ids = StudentCourse.objects.filter(student=user, active=True).values_list('course_id', flat=True) return result.filter(id__in=courses_ids) @detail_route(methods=['GET']) def start(self, request, pk=None):
username = request.GET.get('username', None) user = Student.objects.get(nickname=username) course = Course.objects.get(id=pk) student_course, created = StudentCourse.objects.get_or_create(student=user, course=course) StudentCourse.objects.filter(student=user).update(active=False) student_course.active = True student_course.save() return Response({'success': True})
identifier_body
spendfrom.py
os.path import platform import sys import time from jsonrpc import ServiceProxy, json BASE_FEE=Decimal("0.001") def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision") def determine_db_dir(): """Return the default location of the bitcoin data directory""" if platform.system() == "Darwin": return os.path.expanduser("~/Library/Application Support/Bitcoin/") elif platform.system() == "Windows": return os.path.join(os.environ['APPDATA'], "Bitcoin") return os.path.expanduser("~/.bitcoin") def read_bitcoin_config(dbdir): """Read the bitcoin.conf file from dbdir, returns dictionary of settings""" from ConfigParser import SafeConfigParser class
(object): def __init__(self, fp): self.fp = fp self.sechead = '[all]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: s = self.fp.readline() if s.find('#') != -1: s = s[0:s.find('#')].strip() +"\n" return s config_parser = SafeConfigParser() config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "bitcoin.conf")))) return dict(config_parser.items("all")) def connect_JSON(config): """Connect to a bitcoin JSON-RPC server""" testnet = config.get('testnet', '0') testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False if not 'rpcport' in config: config['rpcport'] = 13338 if testnet else 3338 connect = "http://%s:%[email protected]:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) try: result = ServiceProxy(connect) # ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors, # but also make sure the bitcoind we're talking to is/isn't testnet: if result.getmininginfo()['testnet'] != testnet: sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") sys.exit(1) return result except: sys.stderr.write("Error connecting to RPC server at "+connect+"\n") sys.exit(1) def unlock_wallet(bitcoind): info = bitcoind.getinfo() if 'unlocked_until' not in info: return True # wallet is not encrypted t = int(info['unlocked_until']) if t <= time.time(): try: passphrase = getpass.getpass("Wallet is locked; enter passphrase: ") bitcoind.walletpassphrase(passphrase, 5) except: sys.stderr.write("Wrong passphrase\n") info = bitcoind.getinfo() return int(info['unlocked_until']) > time.time() def list_available(bitcoind): address_summary = dict() address_to_account = dict() for info in bitcoind.listreceivedbyaddress(0): address_to_account[info["address"]] = info["account"] unspent = bitcoind.listunspent(0) for output in unspent: # listunspent doesn't give addresses, so: rawtx = bitcoind.getrawtransaction(output['txid'], 1) vout = rawtx["vout"][output['vout']] pk = vout["scriptPubKey"] # This code only deals with ordinary pay-to-bitcoin-address # or pay-to-script-hash outputs right now; anything exotic is ignored. if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash": continue address = pk["addresses"][0] if address in address_summary: address_summary[address]["total"] += vout["value"] address_summary[address]["outputs"].append(output) else: address_summary[address] = { "total" : vout["value"], "outputs" : [output], "account" : address_to_account.get(address, "") } return address_summary def select_coins(needed, inputs): # Feel free to improve this, this is good enough for my simple needs: outputs = [] have = Decimal("0.0") n = 0 while have < needed and n < len(inputs): outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]}) have += inputs[n]["amount"] n += 1 return (outputs, have-needed) def create_tx(bitcoind, fromaddresses, toaddress, amount, fee): all_coins = list_available(bitcoind) total_available = Decimal("0.0") needed = amount+fee potential_inputs = [] for addr in fromaddresses: if addr not in all_coins: continue potential_inputs.extend(all_coins[addr]["outputs"]) total_available += all_coins[addr]["total"] if total_available < needed: sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed)); sys.exit(1) # # Note: # Python's json/jsonrpc modules have inconsistent support for Decimal numbers. # Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode # Decimals, I'm casting amounts to float before sending them to bitcoind. # outputs = { toaddress : float(amount) } (inputs, change_amount) = select_coins(needed, potential_inputs) if change_amount > BASE_FEE: # don't bother with zero or tiny change change_address = fromaddresses[-1] if change_address in outputs: outputs[change_address] += float(change_amount) else: outputs[change_address] = float(change_amount) rawtx = bitcoind.createrawtransaction(inputs, outputs) signed_rawtx = bitcoind.signrawtransaction(rawtx) if not signed_rawtx["complete"]: sys.stderr.write("signrawtransaction failed\n") sys.exit(1) txdata = signed_rawtx["hex"] return txdata def compute_amount_in(bitcoind, txinfo): result = Decimal("0.0") for vin in txinfo['vin']: in_info = bitcoind.getrawtransaction(vin['txid'], 1) vout = in_info['vout'][vin['vout']] result = result + vout['value'] return result def compute_amount_out(txinfo): result = Decimal("0.0") for vout in txinfo['vout']: result = result + vout['value'] return result def sanity_test_fee(bitcoind, txdata_hex, max_fee): class FeeError(RuntimeError): pass try: txinfo = bitcoind.decoderawtransaction(txdata_hex) total_in = compute_amount_in(bitcoind, txinfo) total_out = compute_amount_out(txinfo) if total_in-total_out > max_fee: raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out)) tx_size = len(txdata_hex)/2 kb = tx_size/1000 # integer division rounds down if kb > 1 and fee < BASE_FEE: raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes") if total_in < 0.01 and fee < BASE_FEE: raise FeeError("Rejecting no-fee, tiny-amount transaction") # Exercise for the reader: compute transaction priority, and # warn if this is a very-low-priority transaction except FeeError as err: sys.stderr.write((str(err)+"\n")) sys.exit(1) def main(): import optparse parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--from", dest="fromaddresses", default=None, help="addresses to get bitcoins from") parser.add_option("--to", dest="to", default=None, help="address to get send bitcoins to") parser.add_option("--amount", dest="amount", default=None, help="amount to send") parser.add_option("--fee", dest="fee", default="0.0", help="fee to include") parser.add_option("--datadir", dest="datadir", default=determine_db_dir(), help="location of bitcoin.conf file with RPC username/password (default: %default)") parser.add_option("--testnet", dest="testnet", default=False, action="store_true", help="Use the test network") parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true", help="Don't broadcast the transaction, just create and print the transaction data") (options,
FakeSecHead
identifier_name
spendfrom.py
)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision") def determine_db_dir(): """Return the default location of the bitcoin data directory""" if platform.system() == "Darwin": return os.path.expanduser("~/Library/Application Support/Bitcoin/") elif platform.system() == "Windows": return os.path.join(os.environ['APPDATA'], "Bitcoin") return os.path.expanduser("~/.bitcoin") def read_bitcoin_config(dbdir): """Read the bitcoin.conf file from dbdir, returns dictionary of settings""" from ConfigParser import SafeConfigParser class FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[all]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: s = self.fp.readline() if s.find('#') != -1: s = s[0:s.find('#')].strip() +"\n" return s config_parser = SafeConfigParser() config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "bitcoin.conf")))) return dict(config_parser.items("all")) def connect_JSON(config): """Connect to a bitcoin JSON-RPC server""" testnet = config.get('testnet', '0') testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False if not 'rpcport' in config: config['rpcport'] = 13338 if testnet else 3338 connect = "http://%s:%[email protected]:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) try: result = ServiceProxy(connect) # ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors, # but also make sure the bitcoind we're talking to is/isn't testnet: if result.getmininginfo()['testnet'] != testnet: sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") sys.exit(1) return result except: sys.stderr.write("Error connecting to RPC server at "+connect+"\n") sys.exit(1) def unlock_wallet(bitcoind): info = bitcoind.getinfo() if 'unlocked_until' not in info: return True # wallet is not encrypted t = int(info['unlocked_until']) if t <= time.time(): try: passphrase = getpass.getpass("Wallet is locked; enter passphrase: ") bitcoind.walletpassphrase(passphrase, 5) except: sys.stderr.write("Wrong passphrase\n") info = bitcoind.getinfo() return int(info['unlocked_until']) > time.time() def list_available(bitcoind): address_summary = dict() address_to_account = dict() for info in bitcoind.listreceivedbyaddress(0): address_to_account[info["address"]] = info["account"] unspent = bitcoind.listunspent(0) for output in unspent: # listunspent doesn't give addresses, so: rawtx = bitcoind.getrawtransaction(output['txid'], 1) vout = rawtx["vout"][output['vout']] pk = vout["scriptPubKey"] # This code only deals with ordinary pay-to-bitcoin-address # or pay-to-script-hash outputs right now; anything exotic is ignored. if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash": continue address = pk["addresses"][0] if address in address_summary: address_summary[address]["total"] += vout["value"] address_summary[address]["outputs"].append(output) else: address_summary[address] = { "total" : vout["value"], "outputs" : [output], "account" : address_to_account.get(address, "") } return address_summary def select_coins(needed, inputs): # Feel free to improve this, this is good enough for my simple needs: outputs = [] have = Decimal("0.0") n = 0 while have < needed and n < len(inputs): outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]}) have += inputs[n]["amount"] n += 1 return (outputs, have-needed) def create_tx(bitcoind, fromaddresses, toaddress, amount, fee): all_coins = list_available(bitcoind) total_available = Decimal("0.0") needed = amount+fee potential_inputs = [] for addr in fromaddresses: if addr not in all_coins: continue potential_inputs.extend(all_coins[addr]["outputs"]) total_available += all_coins[addr]["total"] if total_available < needed: sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed)); sys.exit(1) # # Note: # Python's json/jsonrpc modules have inconsistent support for Decimal numbers. # Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode # Decimals, I'm casting amounts to float before sending them to bitcoind. # outputs = { toaddress : float(amount) } (inputs, change_amount) = select_coins(needed, potential_inputs) if change_amount > BASE_FEE: # don't bother with zero or tiny change change_address = fromaddresses[-1] if change_address in outputs: outputs[change_address] += float(change_amount) else: outputs[change_address] = float(change_amount) rawtx = bitcoind.createrawtransaction(inputs, outputs) signed_rawtx = bitcoind.signrawtransaction(rawtx) if not signed_rawtx["complete"]: sys.stderr.write("signrawtransaction failed\n") sys.exit(1) txdata = signed_rawtx["hex"] return txdata def compute_amount_in(bitcoind, txinfo): result = Decimal("0.0") for vin in txinfo['vin']: in_info = bitcoind.getrawtransaction(vin['txid'], 1) vout = in_info['vout'][vin['vout']] result = result + vout['value'] return result def compute_amount_out(txinfo): result = Decimal("0.0") for vout in txinfo['vout']: result = result + vout['value'] return result def sanity_test_fee(bitcoind, txdata_hex, max_fee): class FeeError(RuntimeError): pass try: txinfo = bitcoind.decoderawtransaction(txdata_hex) total_in = compute_amount_in(bitcoind, txinfo) total_out = compute_amount_out(txinfo) if total_in-total_out > max_fee: raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out)) tx_size = len(txdata_hex)/2 kb = tx_size/1000 # integer division rounds down if kb > 1 and fee < BASE_FEE: raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes") if total_in < 0.01 and fee < BASE_FEE: raise FeeError("Rejecting no-fee, tiny-amount transaction") # Exercise for the reader: compute transaction priority, and # warn if this is a very-low-priority transaction except FeeError as err: sys.stderr.write((str(err)+"\n")) sys.exit(1) def main(): import optparse parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--from", dest="fromaddresses", default=None, help="addresses to get bitcoins from") parser.add_option("--to", dest="to", default=None, help="address to get send bitcoins to") parser.add_option("--amount", dest="amount", default=None, help="amount to send") parser.add_option("--fee", dest="fee", default="0.0", help="fee to include") parser.add_option("--datadir", dest="datadir", default=determine_db_dir(), help="location of bitcoin.conf file with RPC username/password (default: %default)") parser.add_option("--testnet", dest="testnet", default=False, action="store_true", help="Use the test network") parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true", help="Don't broadcast the transaction, just create and print the transaction data") (options, args) = parser.parse_args() check_json_precision() config = read_bitcoin_config(options.datadir) if options.testnet: config['testnet'] = True bitcoind = connect_JSON(config) if options.amount is None:
address_summary = list_available(bitcoind) for address,info in address_summary.iteritems(): n_transactions = len(info['outputs']) if n_transactions > 1:
random_line_split
spendfrom.py
os.path import platform import sys import time from jsonrpc import ServiceProxy, json BASE_FEE=Decimal("0.001") def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision") def determine_db_dir(): """Return the default location of the bitcoin data directory""" if platform.system() == "Darwin": return os.path.expanduser("~/Library/Application Support/Bitcoin/") elif platform.system() == "Windows": return os.path.join(os.environ['APPDATA'], "Bitcoin") return os.path.expanduser("~/.bitcoin") def read_bitcoin_config(dbdir): """Read the bitcoin.conf file from dbdir, returns dictionary of settings""" from ConfigParser import SafeConfigParser class FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[all]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: s = self.fp.readline() if s.find('#') != -1: s = s[0:s.find('#')].strip() +"\n" return s config_parser = SafeConfigParser() config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "bitcoin.conf")))) return dict(config_parser.items("all")) def connect_JSON(config): """Connect to a bitcoin JSON-RPC server""" testnet = config.get('testnet', '0') testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False if not 'rpcport' in config: config['rpcport'] = 13338 if testnet else 3338 connect = "http://%s:%[email protected]:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) try: result = ServiceProxy(connect) # ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors, # but also make sure the bitcoind we're talking to is/isn't testnet: if result.getmininginfo()['testnet'] != testnet: sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") sys.exit(1) return result except: sys.stderr.write("Error connecting to RPC server at "+connect+"\n") sys.exit(1) def unlock_wallet(bitcoind): info = bitcoind.getinfo() if 'unlocked_until' not in info: return True # wallet is not encrypted t = int(info['unlocked_until']) if t <= time.time(): try: passphrase = getpass.getpass("Wallet is locked; enter passphrase: ") bitcoind.walletpassphrase(passphrase, 5) except: sys.stderr.write("Wrong passphrase\n") info = bitcoind.getinfo() return int(info['unlocked_until']) > time.time() def list_available(bitcoind): address_summary = dict() address_to_account = dict() for info in bitcoind.listreceivedbyaddress(0): address_to_account[info["address"]] = info["account"] unspent = bitcoind.listunspent(0) for output in unspent: # listunspent doesn't give addresses, so: rawtx = bitcoind.getrawtransaction(output['txid'], 1) vout = rawtx["vout"][output['vout']] pk = vout["scriptPubKey"] # This code only deals with ordinary pay-to-bitcoin-address # or pay-to-script-hash outputs right now; anything exotic is ignored. if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash": continue address = pk["addresses"][0] if address in address_summary: address_summary[address]["total"] += vout["value"] address_summary[address]["outputs"].append(output) else: address_summary[address] = { "total" : vout["value"], "outputs" : [output], "account" : address_to_account.get(address, "") } return address_summary def select_coins(needed, inputs): # Feel free to improve this, this is good enough for my simple needs:
def create_tx(bitcoind, fromaddresses, toaddress, amount, fee): all_coins = list_available(bitcoind) total_available = Decimal("0.0") needed = amount+fee potential_inputs = [] for addr in fromaddresses: if addr not in all_coins: continue potential_inputs.extend(all_coins[addr]["outputs"]) total_available += all_coins[addr]["total"] if total_available < needed: sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed)); sys.exit(1) # # Note: # Python's json/jsonrpc modules have inconsistent support for Decimal numbers. # Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode # Decimals, I'm casting amounts to float before sending them to bitcoind. # outputs = { toaddress : float(amount) } (inputs, change_amount) = select_coins(needed, potential_inputs) if change_amount > BASE_FEE: # don't bother with zero or tiny change change_address = fromaddresses[-1] if change_address in outputs: outputs[change_address] += float(change_amount) else: outputs[change_address] = float(change_amount) rawtx = bitcoind.createrawtransaction(inputs, outputs) signed_rawtx = bitcoind.signrawtransaction(rawtx) if not signed_rawtx["complete"]: sys.stderr.write("signrawtransaction failed\n") sys.exit(1) txdata = signed_rawtx["hex"] return txdata def compute_amount_in(bitcoind, txinfo): result = Decimal("0.0") for vin in txinfo['vin']: in_info = bitcoind.getrawtransaction(vin['txid'], 1) vout = in_info['vout'][vin['vout']] result = result + vout['value'] return result def compute_amount_out(txinfo): result = Decimal("0.0") for vout in txinfo['vout']: result = result + vout['value'] return result def sanity_test_fee(bitcoind, txdata_hex, max_fee): class FeeError(RuntimeError): pass try: txinfo = bitcoind.decoderawtransaction(txdata_hex) total_in = compute_amount_in(bitcoind, txinfo) total_out = compute_amount_out(txinfo) if total_in-total_out > max_fee: raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out)) tx_size = len(txdata_hex)/2 kb = tx_size/1000 # integer division rounds down if kb > 1 and fee < BASE_FEE: raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes") if total_in < 0.01 and fee < BASE_FEE: raise FeeError("Rejecting no-fee, tiny-amount transaction") # Exercise for the reader: compute transaction priority, and # warn if this is a very-low-priority transaction except FeeError as err: sys.stderr.write((str(err)+"\n")) sys.exit(1) def main(): import optparse parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--from", dest="fromaddresses", default=None, help="addresses to get bitcoins from") parser.add_option("--to", dest="to", default=None, help="address to get send bitcoins to") parser.add_option("--amount", dest="amount", default=None, help="amount to send") parser.add_option("--fee", dest="fee", default="0.0", help="fee to include") parser.add_option("--datadir", dest="datadir", default=determine_db_dir(), help="location of bitcoin.conf file with RPC username/password (default: %default)") parser.add_option("--testnet", dest="testnet", default=False, action="store_true", help="Use the test network") parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true", help="Don't broadcast the transaction, just create and print the transaction data") (options,
outputs = [] have = Decimal("0.0") n = 0 while have < needed and n < len(inputs): outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]}) have += inputs[n]["amount"] n += 1 return (outputs, have-needed)
identifier_body
spendfrom.py
os.path import platform import sys import time from jsonrpc import ServiceProxy, json BASE_FEE=Decimal("0.001") def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision") def determine_db_dir(): """Return the default location of the bitcoin data directory""" if platform.system() == "Darwin": return os.path.expanduser("~/Library/Application Support/Bitcoin/") elif platform.system() == "Windows": return os.path.join(os.environ['APPDATA'], "Bitcoin") return os.path.expanduser("~/.bitcoin") def read_bitcoin_config(dbdir): """Read the bitcoin.conf file from dbdir, returns dictionary of settings""" from ConfigParser import SafeConfigParser class FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[all]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: s = self.fp.readline() if s.find('#') != -1: s = s[0:s.find('#')].strip() +"\n" return s config_parser = SafeConfigParser() config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "bitcoin.conf")))) return dict(config_parser.items("all")) def connect_JSON(config): """Connect to a bitcoin JSON-RPC server""" testnet = config.get('testnet', '0') testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False if not 'rpcport' in config: config['rpcport'] = 13338 if testnet else 3338 connect = "http://%s:%[email protected]:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) try: result = ServiceProxy(connect) # ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors, # but also make sure the bitcoind we're talking to is/isn't testnet: if result.getmininginfo()['testnet'] != testnet: sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") sys.exit(1) return result except: sys.stderr.write("Error connecting to RPC server at "+connect+"\n") sys.exit(1) def unlock_wallet(bitcoind): info = bitcoind.getinfo() if 'unlocked_until' not in info: return True # wallet is not encrypted t = int(info['unlocked_until']) if t <= time.time(): try: passphrase = getpass.getpass("Wallet is locked; enter passphrase: ") bitcoind.walletpassphrase(passphrase, 5) except: sys.stderr.write("Wrong passphrase\n") info = bitcoind.getinfo() return int(info['unlocked_until']) > time.time() def list_available(bitcoind): address_summary = dict() address_to_account = dict() for info in bitcoind.listreceivedbyaddress(0): address_to_account[info["address"]] = info["account"] unspent = bitcoind.listunspent(0) for output in unspent: # listunspent doesn't give addresses, so: rawtx = bitcoind.getrawtransaction(output['txid'], 1) vout = rawtx["vout"][output['vout']] pk = vout["scriptPubKey"] # This code only deals with ordinary pay-to-bitcoin-address # or pay-to-script-hash outputs right now; anything exotic is ignored. if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash": continue address = pk["addresses"][0] if address in address_summary: address_summary[address]["total"] += vout["value"] address_summary[address]["outputs"].append(output) else: address_summary[address] = { "total" : vout["value"], "outputs" : [output], "account" : address_to_account.get(address, "") } return address_summary def select_coins(needed, inputs): # Feel free to improve this, this is good enough for my simple needs: outputs = [] have = Decimal("0.0") n = 0 while have < needed and n < len(inputs): outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]}) have += inputs[n]["amount"] n += 1 return (outputs, have-needed) def create_tx(bitcoind, fromaddresses, toaddress, amount, fee): all_coins = list_available(bitcoind) total_available = Decimal("0.0") needed = amount+fee potential_inputs = [] for addr in fromaddresses: if addr not in all_coins: continue potential_inputs.extend(all_coins[addr]["outputs"]) total_available += all_coins[addr]["total"] if total_available < needed: sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed)); sys.exit(1) # # Note: # Python's json/jsonrpc modules have inconsistent support for Decimal numbers. # Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode # Decimals, I'm casting amounts to float before sending them to bitcoind. # outputs = { toaddress : float(amount) } (inputs, change_amount) = select_coins(needed, potential_inputs) if change_amount > BASE_FEE: # don't bother with zero or tiny change
rawtx = bitcoind.createrawtransaction(inputs, outputs) signed_rawtx = bitcoind.signrawtransaction(rawtx) if not signed_rawtx["complete"]: sys.stderr.write("signrawtransaction failed\n") sys.exit(1) txdata = signed_rawtx["hex"] return txdata def compute_amount_in(bitcoind, txinfo): result = Decimal("0.0") for vin in txinfo['vin']: in_info = bitcoind.getrawtransaction(vin['txid'], 1) vout = in_info['vout'][vin['vout']] result = result + vout['value'] return result def compute_amount_out(txinfo): result = Decimal("0.0") for vout in txinfo['vout']: result = result + vout['value'] return result def sanity_test_fee(bitcoind, txdata_hex, max_fee): class FeeError(RuntimeError): pass try: txinfo = bitcoind.decoderawtransaction(txdata_hex) total_in = compute_amount_in(bitcoind, txinfo) total_out = compute_amount_out(txinfo) if total_in-total_out > max_fee: raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out)) tx_size = len(txdata_hex)/2 kb = tx_size/1000 # integer division rounds down if kb > 1 and fee < BASE_FEE: raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes") if total_in < 0.01 and fee < BASE_FEE: raise FeeError("Rejecting no-fee, tiny-amount transaction") # Exercise for the reader: compute transaction priority, and # warn if this is a very-low-priority transaction except FeeError as err: sys.stderr.write((str(err)+"\n")) sys.exit(1) def main(): import optparse parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--from", dest="fromaddresses", default=None, help="addresses to get bitcoins from") parser.add_option("--to", dest="to", default=None, help="address to get send bitcoins to") parser.add_option("--amount", dest="amount", default=None, help="amount to send") parser.add_option("--fee", dest="fee", default="0.0", help="fee to include") parser.add_option("--datadir", dest="datadir", default=determine_db_dir(), help="location of bitcoin.conf file with RPC username/password (default: %default)") parser.add_option("--testnet", dest="testnet", default=False, action="store_true", help="Use the test network") parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true", help="Don't broadcast the transaction, just create and print the transaction data") (options,
change_address = fromaddresses[-1] if change_address in outputs: outputs[change_address] += float(change_amount) else: outputs[change_address] = float(change_amount)
conditional_block
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! partial_eq_impl { // ($($t:ty)*) => ($( // #[stable(feature = "rust1", since = "1.0.0")] // impl PartialEq for $t { // #[inline] // fn eq(&self, other: &$t) -> bool { (*self) == (*other) } // #[inline] // fn ne(&self, other: &$t) -> bool { (*self) != (*other) } // } // )*) // } // partial_eq_impl! { // bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 // } macro_rules! ne_test { ($($t:ty)*) => ($({ let v1: $t = 68 as $t; { let result: bool = v1.ne(&v1); assert_eq!(result, false); } let v2: $t = 100 as $t; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } })*) } #[test] fn
() { let v1: bool = false; { let result: bool = v1.ne(&v1); assert_eq!(result, false); } let v2: bool = true; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } } #[test] fn ne_test2() { ne_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }; } }
ne_test1
identifier_name
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! partial_eq_impl { // ($($t:ty)*) => ($( // #[stable(feature = "rust1", since = "1.0.0")] // impl PartialEq for $t { // #[inline] // fn eq(&self, other: &$t) -> bool { (*self) == (*other) } // #[inline] // fn ne(&self, other: &$t) -> bool { (*self) != (*other) } // } // )*) // } // partial_eq_impl! { // bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 // } macro_rules! ne_test { ($($t:ty)*) => ($({ let v1: $t = 68 as $t;
let v2: $t = 100 as $t; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } })*) } #[test] fn ne_test1() { let v1: bool = false; { let result: bool = v1.ne(&v1); assert_eq!(result, false); } let v2: bool = true; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } } #[test] fn ne_test2() { ne_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }; } }
{ let result: bool = v1.ne(&v1); assert_eq!(result, false); }
random_line_split
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! partial_eq_impl { // ($($t:ty)*) => ($( // #[stable(feature = "rust1", since = "1.0.0")] // impl PartialEq for $t { // #[inline] // fn eq(&self, other: &$t) -> bool { (*self) == (*other) } // #[inline] // fn ne(&self, other: &$t) -> bool { (*self) != (*other) } // } // )*) // } // partial_eq_impl! { // bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 // } macro_rules! ne_test { ($($t:ty)*) => ($({ let v1: $t = 68 as $t; { let result: bool = v1.ne(&v1); assert_eq!(result, false); } let v2: $t = 100 as $t; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } })*) } #[test] fn ne_test1() { let v1: bool = false; { let result: bool = v1.ne(&v1); assert_eq!(result, false); } let v2: bool = true; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } } #[test] fn ne_test2()
}
{ ne_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }; }
identifier_body
editor-socketio-server.js
'use strict'; var EventEmitter = require('events').EventEmitter; var TextOperation = require('./text-operation'); var WrappedOperation = require('./wrapped-operation'); var Server = require('./server'); var Selection = require('./selection'); var util = require('util'); var LZString = require('lz-string'); var logger = require('../logger'); function EditorSocketIOServer(document, operations, docId, mayWrite, operationCallback)
util.inherits(EditorSocketIOServer, Server); extend(EditorSocketIOServer.prototype, EventEmitter.prototype); function extend(target, source) { for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } } EditorSocketIOServer.prototype.addClient = function (socket) { var self = this; socket.join(this.docId); var docOut = { str: this.document, revision: this.operations.length, clients: this.users }; socket.emit('doc', LZString.compressToUTF16(JSON.stringify(docOut))); socket.on('operation', function (revision, operation, selection) { operation = LZString.decompressFromUTF16(operation); operation = JSON.parse(operation); socket.origin = 'operation'; self.mayWrite(socket, function (mayWrite) { if (!mayWrite) { console.log("User doesn't have the right to edit."); return; } try { self.onOperation(socket, revision, operation, selection); if (typeof self.operationCallback === 'function') self.operationCallback(socket, operation); } catch (err) { socket.disconnect(true); } }); }); socket.on('get_operations', function (base, head) { self.onGetOperations(socket, base, head); }); socket.on('selection', function (obj) { socket.origin = 'selection'; self.mayWrite(socket, function (mayWrite) { if (!mayWrite) { console.log("User doesn't have the right to edit."); return; } self.updateSelection(socket, obj && Selection.fromJSON(obj)); }); }); socket.on('disconnect', function () { //console.log("Disconnect"); socket.leave(self.docId); self.onDisconnect(socket); /* if (socket.manager && socket.manager.sockets.clients(self.docId).length === 0) { self.emit('empty-room'); } */ }); }; EditorSocketIOServer.prototype.onOperation = function (socket, revision, operation, selection) { var wrapped; try { wrapped = new WrappedOperation( TextOperation.fromJSON(operation), selection && Selection.fromJSON(selection) ); } catch (exc) { logger.error("Invalid operation received: "); logger.error(exc); throw new Error(exc); } try { var clientId = socket.id; var wrappedPrime = this.receiveOperation(revision, wrapped); if(!wrappedPrime) return; //console.log("new operation: " + JSON.stringify(wrapped)); this.getClient(clientId).selection = wrappedPrime.meta; revision = this.operations.length; socket.emit('ack', revision); socket.broadcast.in(this.docId).emit( 'operation', clientId, revision, wrappedPrime.wrapped.toJSON(), wrappedPrime.meta ); //set document is dirty this.isDirty = true; } catch (exc) { logger.error(exc); throw new Error(exc); } }; EditorSocketIOServer.prototype.onGetOperations = function (socket, base, head) { var operations = this.operations.slice(base, head).map(function (op) { return op.wrapped.toJSON(); }); operations = LZString.compressToUTF16(JSON.stringify(operations)); socket.emit('operations', head, operations); }; EditorSocketIOServer.prototype.updateSelection = function (socket, selection) { var clientId = socket.id; if (selection) { this.getClient(clientId).selection = selection; } else { delete this.getClient(clientId).selection; } socket.broadcast.to(this.docId).emit('selection', clientId, selection); }; EditorSocketIOServer.prototype.setName = function (socket, name) { var clientId = socket.id; this.getClient(clientId).name = name; socket.broadcast.to(this.docId).emit('set_name', clientId, name); }; EditorSocketIOServer.prototype.setColor = function (socket, color) { var clientId = socket.id; this.getClient(clientId).color = color; socket.broadcast.to(this.docId).emit('set_color', clientId, color); }; EditorSocketIOServer.prototype.getClient = function (clientId) { return this.users[clientId] || (this.users[clientId] = {}); }; EditorSocketIOServer.prototype.onDisconnect = function (socket) { var clientId = socket.id; delete this.users[clientId]; socket.broadcast.to(this.docId).emit('client_left', clientId); }; module.exports = EditorSocketIOServer;
{ EventEmitter.call(this); Server.call(this, document, operations); this.users = {}; this.docId = docId; this.mayWrite = mayWrite || function (_, cb) { cb(true); }; this.operationCallback = operationCallback; }
identifier_body
editor-socketio-server.js
'use strict'; var EventEmitter = require('events').EventEmitter; var TextOperation = require('./text-operation'); var WrappedOperation = require('./wrapped-operation'); var Server = require('./server'); var Selection = require('./selection'); var util = require('util'); var LZString = require('lz-string'); var logger = require('../logger'); function EditorSocketIOServer(document, operations, docId, mayWrite, operationCallback) { EventEmitter.call(this); Server.call(this, document, operations); this.users = {}; this.docId = docId; this.mayWrite = mayWrite || function (_, cb) { cb(true); }; this.operationCallback = operationCallback; } util.inherits(EditorSocketIOServer, Server); extend(EditorSocketIOServer.prototype, EventEmitter.prototype); function
(target, source) { for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } } EditorSocketIOServer.prototype.addClient = function (socket) { var self = this; socket.join(this.docId); var docOut = { str: this.document, revision: this.operations.length, clients: this.users }; socket.emit('doc', LZString.compressToUTF16(JSON.stringify(docOut))); socket.on('operation', function (revision, operation, selection) { operation = LZString.decompressFromUTF16(operation); operation = JSON.parse(operation); socket.origin = 'operation'; self.mayWrite(socket, function (mayWrite) { if (!mayWrite) { console.log("User doesn't have the right to edit."); return; } try { self.onOperation(socket, revision, operation, selection); if (typeof self.operationCallback === 'function') self.operationCallback(socket, operation); } catch (err) { socket.disconnect(true); } }); }); socket.on('get_operations', function (base, head) { self.onGetOperations(socket, base, head); }); socket.on('selection', function (obj) { socket.origin = 'selection'; self.mayWrite(socket, function (mayWrite) { if (!mayWrite) { console.log("User doesn't have the right to edit."); return; } self.updateSelection(socket, obj && Selection.fromJSON(obj)); }); }); socket.on('disconnect', function () { //console.log("Disconnect"); socket.leave(self.docId); self.onDisconnect(socket); /* if (socket.manager && socket.manager.sockets.clients(self.docId).length === 0) { self.emit('empty-room'); } */ }); }; EditorSocketIOServer.prototype.onOperation = function (socket, revision, operation, selection) { var wrapped; try { wrapped = new WrappedOperation( TextOperation.fromJSON(operation), selection && Selection.fromJSON(selection) ); } catch (exc) { logger.error("Invalid operation received: "); logger.error(exc); throw new Error(exc); } try { var clientId = socket.id; var wrappedPrime = this.receiveOperation(revision, wrapped); if(!wrappedPrime) return; //console.log("new operation: " + JSON.stringify(wrapped)); this.getClient(clientId).selection = wrappedPrime.meta; revision = this.operations.length; socket.emit('ack', revision); socket.broadcast.in(this.docId).emit( 'operation', clientId, revision, wrappedPrime.wrapped.toJSON(), wrappedPrime.meta ); //set document is dirty this.isDirty = true; } catch (exc) { logger.error(exc); throw new Error(exc); } }; EditorSocketIOServer.prototype.onGetOperations = function (socket, base, head) { var operations = this.operations.slice(base, head).map(function (op) { return op.wrapped.toJSON(); }); operations = LZString.compressToUTF16(JSON.stringify(operations)); socket.emit('operations', head, operations); }; EditorSocketIOServer.prototype.updateSelection = function (socket, selection) { var clientId = socket.id; if (selection) { this.getClient(clientId).selection = selection; } else { delete this.getClient(clientId).selection; } socket.broadcast.to(this.docId).emit('selection', clientId, selection); }; EditorSocketIOServer.prototype.setName = function (socket, name) { var clientId = socket.id; this.getClient(clientId).name = name; socket.broadcast.to(this.docId).emit('set_name', clientId, name); }; EditorSocketIOServer.prototype.setColor = function (socket, color) { var clientId = socket.id; this.getClient(clientId).color = color; socket.broadcast.to(this.docId).emit('set_color', clientId, color); }; EditorSocketIOServer.prototype.getClient = function (clientId) { return this.users[clientId] || (this.users[clientId] = {}); }; EditorSocketIOServer.prototype.onDisconnect = function (socket) { var clientId = socket.id; delete this.users[clientId]; socket.broadcast.to(this.docId).emit('client_left', clientId); }; module.exports = EditorSocketIOServer;
extend
identifier_name
editor-socketio-server.js
'use strict'; var EventEmitter = require('events').EventEmitter; var TextOperation = require('./text-operation'); var WrappedOperation = require('./wrapped-operation'); var Server = require('./server'); var Selection = require('./selection'); var util = require('util'); var LZString = require('lz-string'); var logger = require('../logger'); function EditorSocketIOServer(document, operations, docId, mayWrite, operationCallback) { EventEmitter.call(this); Server.call(this, document, operations); this.users = {}; this.docId = docId; this.mayWrite = mayWrite || function (_, cb) { cb(true); }; this.operationCallback = operationCallback; } util.inherits(EditorSocketIOServer, Server); extend(EditorSocketIOServer.prototype, EventEmitter.prototype); function extend(target, source) { for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } } EditorSocketIOServer.prototype.addClient = function (socket) { var self = this; socket.join(this.docId); var docOut = { str: this.document, revision: this.operations.length, clients: this.users }; socket.emit('doc', LZString.compressToUTF16(JSON.stringify(docOut))); socket.on('operation', function (revision, operation, selection) { operation = LZString.decompressFromUTF16(operation); operation = JSON.parse(operation); socket.origin = 'operation'; self.mayWrite(socket, function (mayWrite) { if (!mayWrite) { console.log("User doesn't have the right to edit."); return; } try { self.onOperation(socket, revision, operation, selection); if (typeof self.operationCallback === 'function') self.operationCallback(socket, operation); } catch (err) { socket.disconnect(true); } }); }); socket.on('get_operations', function (base, head) { self.onGetOperations(socket, base, head); }); socket.on('selection', function (obj) { socket.origin = 'selection'; self.mayWrite(socket, function (mayWrite) { if (!mayWrite)
self.updateSelection(socket, obj && Selection.fromJSON(obj)); }); }); socket.on('disconnect', function () { //console.log("Disconnect"); socket.leave(self.docId); self.onDisconnect(socket); /* if (socket.manager && socket.manager.sockets.clients(self.docId).length === 0) { self.emit('empty-room'); } */ }); }; EditorSocketIOServer.prototype.onOperation = function (socket, revision, operation, selection) { var wrapped; try { wrapped = new WrappedOperation( TextOperation.fromJSON(operation), selection && Selection.fromJSON(selection) ); } catch (exc) { logger.error("Invalid operation received: "); logger.error(exc); throw new Error(exc); } try { var clientId = socket.id; var wrappedPrime = this.receiveOperation(revision, wrapped); if(!wrappedPrime) return; //console.log("new operation: " + JSON.stringify(wrapped)); this.getClient(clientId).selection = wrappedPrime.meta; revision = this.operations.length; socket.emit('ack', revision); socket.broadcast.in(this.docId).emit( 'operation', clientId, revision, wrappedPrime.wrapped.toJSON(), wrappedPrime.meta ); //set document is dirty this.isDirty = true; } catch (exc) { logger.error(exc); throw new Error(exc); } }; EditorSocketIOServer.prototype.onGetOperations = function (socket, base, head) { var operations = this.operations.slice(base, head).map(function (op) { return op.wrapped.toJSON(); }); operations = LZString.compressToUTF16(JSON.stringify(operations)); socket.emit('operations', head, operations); }; EditorSocketIOServer.prototype.updateSelection = function (socket, selection) { var clientId = socket.id; if (selection) { this.getClient(clientId).selection = selection; } else { delete this.getClient(clientId).selection; } socket.broadcast.to(this.docId).emit('selection', clientId, selection); }; EditorSocketIOServer.prototype.setName = function (socket, name) { var clientId = socket.id; this.getClient(clientId).name = name; socket.broadcast.to(this.docId).emit('set_name', clientId, name); }; EditorSocketIOServer.prototype.setColor = function (socket, color) { var clientId = socket.id; this.getClient(clientId).color = color; socket.broadcast.to(this.docId).emit('set_color', clientId, color); }; EditorSocketIOServer.prototype.getClient = function (clientId) { return this.users[clientId] || (this.users[clientId] = {}); }; EditorSocketIOServer.prototype.onDisconnect = function (socket) { var clientId = socket.id; delete this.users[clientId]; socket.broadcast.to(this.docId).emit('client_left', clientId); }; module.exports = EditorSocketIOServer;
{ console.log("User doesn't have the right to edit."); return; }
conditional_block
editor-socketio-server.js
'use strict'; var EventEmitter = require('events').EventEmitter; var TextOperation = require('./text-operation'); var WrappedOperation = require('./wrapped-operation'); var Server = require('./server'); var Selection = require('./selection'); var util = require('util'); var LZString = require('lz-string'); var logger = require('../logger'); function EditorSocketIOServer(document, operations, docId, mayWrite, operationCallback) { EventEmitter.call(this); Server.call(this, document, operations); this.users = {}; this.docId = docId; this.mayWrite = mayWrite || function (_, cb) { cb(true); }; this.operationCallback = operationCallback; } util.inherits(EditorSocketIOServer, Server); extend(EditorSocketIOServer.prototype, EventEmitter.prototype); function extend(target, source) { for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } } EditorSocketIOServer.prototype.addClient = function (socket) { var self = this; socket.join(this.docId); var docOut = { str: this.document, revision: this.operations.length, clients: this.users }; socket.emit('doc', LZString.compressToUTF16(JSON.stringify(docOut))); socket.on('operation', function (revision, operation, selection) { operation = LZString.decompressFromUTF16(operation); operation = JSON.parse(operation); socket.origin = 'operation'; self.mayWrite(socket, function (mayWrite) { if (!mayWrite) { console.log("User doesn't have the right to edit."); return; } try { self.onOperation(socket, revision, operation, selection); if (typeof self.operationCallback === 'function') self.operationCallback(socket, operation); } catch (err) { socket.disconnect(true); } }); }); socket.on('get_operations', function (base, head) { self.onGetOperations(socket, base, head); }); socket.on('selection', function (obj) { socket.origin = 'selection'; self.mayWrite(socket, function (mayWrite) { if (!mayWrite) { console.log("User doesn't have the right to edit."); return; } self.updateSelection(socket, obj && Selection.fromJSON(obj)); }); }); socket.on('disconnect', function () { //console.log("Disconnect"); socket.leave(self.docId); self.onDisconnect(socket); /* if (socket.manager && socket.manager.sockets.clients(self.docId).length === 0) { self.emit('empty-room'); } */ }); }; EditorSocketIOServer.prototype.onOperation = function (socket, revision, operation, selection) { var wrapped; try { wrapped = new WrappedOperation( TextOperation.fromJSON(operation), selection && Selection.fromJSON(selection) ); } catch (exc) { logger.error("Invalid operation received: "); logger.error(exc); throw new Error(exc); } try { var clientId = socket.id; var wrappedPrime = this.receiveOperation(revision, wrapped); if(!wrappedPrime) return; //console.log("new operation: " + JSON.stringify(wrapped)); this.getClient(clientId).selection = wrappedPrime.meta; revision = this.operations.length; socket.emit('ack', revision); socket.broadcast.in(this.docId).emit( 'operation', clientId, revision, wrappedPrime.wrapped.toJSON(), wrappedPrime.meta ); //set document is dirty this.isDirty = true; } catch (exc) { logger.error(exc); throw new Error(exc); } }; EditorSocketIOServer.prototype.onGetOperations = function (socket, base, head) { var operations = this.operations.slice(base, head).map(function (op) { return op.wrapped.toJSON(); }); operations = LZString.compressToUTF16(JSON.stringify(operations)); socket.emit('operations', head, operations); }; EditorSocketIOServer.prototype.updateSelection = function (socket, selection) { var clientId = socket.id; if (selection) { this.getClient(clientId).selection = selection; } else { delete this.getClient(clientId).selection; } socket.broadcast.to(this.docId).emit('selection', clientId, selection); }; EditorSocketIOServer.prototype.setName = function (socket, name) { var clientId = socket.id; this.getClient(clientId).name = name; socket.broadcast.to(this.docId).emit('set_name', clientId, name); }; EditorSocketIOServer.prototype.setColor = function (socket, color) { var clientId = socket.id; this.getClient(clientId).color = color; socket.broadcast.to(this.docId).emit('set_color', clientId, color); }; EditorSocketIOServer.prototype.getClient = function (clientId) { return this.users[clientId] || (this.users[clientId] = {}); }; EditorSocketIOServer.prototype.onDisconnect = function (socket) {
module.exports = EditorSocketIOServer;
var clientId = socket.id; delete this.users[clientId]; socket.broadcast.to(this.docId).emit('client_left', clientId); };
random_line_split
webpack.config.js
const webpack = require('atool-build/lib/webpack'); module.exports = function (webpackConfig, env) { webpackConfig.babel.plugins.push('transform-runtime'); webpackConfig.babel.plugins.push(['import', { libraryName: 'antd', style: 'css' // if true, use less }]); // Support hmr if (env === 'development') { webpackConfig.devtool = '#eval'; webpackConfig.babel.plugins.push('dva-hmr'); } else { webpackConfig.babel.plugins.push('dev-expression'); } // Don't extract common.js and common.css webpackConfig.plugins = webpackConfig.plugins.filter(function (plugin) { return !(plugin instanceof webpack.optimize.CommonsChunkPlugin); }); // Support CSS Modules // Parse all less files as css module. webpackConfig.module.loaders.forEach(function (loader, index) { if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.less$') > -1) { loader.include = /node_modules/; loader.test = /\.less$/; } if (loader.test.toString() === '/\\.module\\.less$/') { loader.exclude = /node_modules/; loader.test = /\.less$/; } if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.css$') > -1)
if (loader.test.toString() === '/\\.module\\.css$/') { loader.exclude = /node_modules/; loader.test = /\.css$/; } }); return webpackConfig; };
{ loader.include = /node_modules/; loader.test = /\.css$/; }
conditional_block
webpack.config.js
const webpack = require('atool-build/lib/webpack'); module.exports = function (webpackConfig, env) { webpackConfig.babel.plugins.push('transform-runtime'); webpackConfig.babel.plugins.push(['import', { libraryName: 'antd', style: 'css' // if true, use less }]); // Support hmr if (env === 'development') { webpackConfig.devtool = '#eval'; webpackConfig.babel.plugins.push('dva-hmr'); } else { webpackConfig.babel.plugins.push('dev-expression'); } // Don't extract common.js and common.css webpackConfig.plugins = webpackConfig.plugins.filter(function (plugin) { return !(plugin instanceof webpack.optimize.CommonsChunkPlugin); }); // Support CSS Modules // Parse all less files as css module. webpackConfig.module.loaders.forEach(function (loader, index) { if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.less$') > -1) { loader.include = /node_modules/; loader.test = /\.less$/; } if (loader.test.toString() === '/\\.module\\.less$/') { loader.exclude = /node_modules/; loader.test = /\.less$/; } if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.css$') > -1) { loader.include = /node_modules/; loader.test = /\.css$/; } if (loader.test.toString() === '/\\.module\\.css$/') { loader.exclude = /node_modules/; loader.test = /\.css$/; } });
return webpackConfig; };
random_line_split
mod.rs
extern crate rmp; use std; quick_error! { #[derive(Debug)] pub enum DBError { Protocol(err: String) { description("Protocol error") display("Protocol error: {}", err) } FileFormat(err: String) { description("File fromat error") display("File format error: {}", err) } ParseString(err: String) { description("Parse string error") display("Parse string error") from(rmp::decode::DecodeStringError) } ParseValue(err: rmp::decode::ValueReadError){ description("Parse value error") display("Parse value error: {}", err) from() cause(err) } SendValue(err: rmp::encode::ValueWriteError){ description("Send value error") display("Send value error: {}", err) from() cause(err) } UTF8(err: std::string::FromUtf8Error){ description("UTF decoding error") display("UTF encoding error: {}", err) from() cause(err) } IO(err: std::io::Error){
description("IO error") display("IO error: {}", err) from() cause(err) } } }
random_line_split
if-check-panic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:Number is odd fn even(x: usize) -> bool { if x < 2 { return false; } else if x == 2
else { return even(x - 2); } } fn foo(x: usize) { if even(x) { println!("{}", x); } else { panic!("Number is odd"); } } fn main() { foo(3); }
{ return true; }
conditional_block
if-check-panic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:Number is odd fn even(x: usize) -> bool { if x < 2 { return false; } else if x == 2 { return true; } else { return even(x - 2); } }
println!("{}", x); } else { panic!("Number is odd"); } } fn main() { foo(3); }
fn foo(x: usize) { if even(x) {
random_line_split
if-check-panic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:Number is odd fn even(x: usize) -> bool { if x < 2 { return false; } else if x == 2 { return true; } else { return even(x - 2); } } fn
(x: usize) { if even(x) { println!("{}", x); } else { panic!("Number is odd"); } } fn main() { foo(3); }
foo
identifier_name
if-check-panic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:Number is odd fn even(x: usize) -> bool
fn foo(x: usize) { if even(x) { println!("{}", x); } else { panic!("Number is odd"); } } fn main() { foo(3); }
{ if x < 2 { return false; } else if x == 2 { return true; } else { return even(x - 2); } }
identifier_body
selectnav.js
/* JavaScript Dynamic Select Navigation v1.0.0 by Todd Motto: http://www.toddmotto.com Latest version: https://github.com/toddmotto/selectnav Copyright 2013 Todd Motto Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php Dynamically creates a select menu with nested capabilities */ function
() { var select = document.createElement('select'); var first = document.createElement('option'); first.innerHTML = 'Navigation'; first.setAttribute('selected', 'selected'); select.setAttribute('id', 'mobile'); select.appendChild(first); var nav = document.getElementById('nav'); var loadLinks = function(element, hyphen, level) { var e = element; if (e) { var children = e.children; for(var i = 0; i < e.children.length; ++i) { var currentLink = children[i]; switch(currentLink.nodeName) { case 'A': var option = document.createElement('option'); option.innerHTML = (level++ < 1 ? '' : hyphen) + currentLink.innerHTML; option.value = currentLink.href; select.appendChild(option); break; default: if(currentLink.nodeName === 'UL') { (level < 2) || (hyphen += hyphen); } loadLinks(currentLink, hyphen, level); break; } } } } loadLinks(nav, '- ', 0); if (nav) nav.appendChild(select); var mobile = document.getElementById('mobile'); if (mobile) { if(mobile.addEventListener) { mobile.addEventListener('change', function () { window.location.href = mobile.options[mobile.selectedIndex].value; }); } else if(mobile.attachEvent) { mobile.attachEvent('onchange', function () { window.location.href = mobile.options[mobile.selectedIndex].value; }); } else { mobile.onchange = function () { window.location.href = mobile.options[mobile.selectedIndex].value; } } } }
selectnav
identifier_name
selectnav.js
/* JavaScript Dynamic Select Navigation v1.0.0 by Todd Motto: http://www.toddmotto.com Latest version: https://github.com/toddmotto/selectnav Copyright 2013 Todd Motto Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php Dynamically creates a select menu with nested capabilities */ function selectnav() { var select = document.createElement('select'); var first = document.createElement('option'); first.innerHTML = 'Navigation'; first.setAttribute('selected', 'selected'); select.setAttribute('id', 'mobile'); select.appendChild(first); var nav = document.getElementById('nav'); var loadLinks = function(element, hyphen, level) { var e = element; if (e) { var children = e.children; for(var i = 0; i < e.children.length; ++i) { var currentLink = children[i]; switch(currentLink.nodeName) { case 'A': var option = document.createElement('option'); option.innerHTML = (level++ < 1 ? '' : hyphen) + currentLink.innerHTML; option.value = currentLink.href; select.appendChild(option); break; default: if(currentLink.nodeName === 'UL') { (level < 2) || (hyphen += hyphen); } loadLinks(currentLink, hyphen, level); break; } } } } loadLinks(nav, '- ', 0); if (nav) nav.appendChild(select); var mobile = document.getElementById('mobile'); if (mobile) { if(mobile.addEventListener) { mobile.addEventListener('change', function () { window.location.href = mobile.options[mobile.selectedIndex].value; }); } else if(mobile.attachEvent) { mobile.attachEvent('onchange', function () { window.location.href = mobile.options[mobile.selectedIndex].value; }); } else { mobile.onchange = function () { window.location.href = mobile.options[mobile.selectedIndex].value; } } }
}
random_line_split
selectnav.js
/* JavaScript Dynamic Select Navigation v1.0.0 by Todd Motto: http://www.toddmotto.com Latest version: https://github.com/toddmotto/selectnav Copyright 2013 Todd Motto Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php Dynamically creates a select menu with nested capabilities */ function selectnav() { var select = document.createElement('select'); var first = document.createElement('option'); first.innerHTML = 'Navigation'; first.setAttribute('selected', 'selected'); select.setAttribute('id', 'mobile'); select.appendChild(first); var nav = document.getElementById('nav'); var loadLinks = function(element, hyphen, level) { var e = element; if (e) { var children = e.children; for(var i = 0; i < e.children.length; ++i) { var currentLink = children[i]; switch(currentLink.nodeName) { case 'A': var option = document.createElement('option'); option.innerHTML = (level++ < 1 ? '' : hyphen) + currentLink.innerHTML; option.value = currentLink.href; select.appendChild(option); break; default: if(currentLink.nodeName === 'UL') { (level < 2) || (hyphen += hyphen); } loadLinks(currentLink, hyphen, level); break; } } } } loadLinks(nav, '- ', 0); if (nav) nav.appendChild(select); var mobile = document.getElementById('mobile'); if (mobile)
}
{ if(mobile.addEventListener) { mobile.addEventListener('change', function () { window.location.href = mobile.options[mobile.selectedIndex].value; }); } else if(mobile.attachEvent) { mobile.attachEvent('onchange', function () { window.location.href = mobile.options[mobile.selectedIndex].value; }); } else { mobile.onchange = function () { window.location.href = mobile.options[mobile.selectedIndex].value; } } }
conditional_block
selectnav.js
/* JavaScript Dynamic Select Navigation v1.0.0 by Todd Motto: http://www.toddmotto.com Latest version: https://github.com/toddmotto/selectnav Copyright 2013 Todd Motto Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php Dynamically creates a select menu with nested capabilities */ function selectnav()
switch(currentLink.nodeName) { case 'A': var option = document.createElement('option'); option.innerHTML = (level++ < 1 ? '' : hyphen) + currentLink.innerHTML; option.value = currentLink.href; select.appendChild(option); break; default: if(currentLink.nodeName === 'UL') { (level < 2) || (hyphen += hyphen); } loadLinks(currentLink, hyphen, level); break; } } } } loadLinks(nav, '- ', 0); if (nav) nav.appendChild(select); var mobile = document.getElementById('mobile'); if (mobile) { if(mobile.addEventListener) { mobile.addEventListener('change', function () { window.location.href = mobile.options[mobile.selectedIndex].value; }); } else if(mobile.attachEvent) { mobile.attachEvent('onchange', function () { window.location.href = mobile.options[mobile.selectedIndex].value; }); } else { mobile.onchange = function () { window.location.href = mobile.options[mobile.selectedIndex].value; } } } }
{ var select = document.createElement('select'); var first = document.createElement('option'); first.innerHTML = 'Navigation'; first.setAttribute('selected', 'selected'); select.setAttribute('id', 'mobile'); select.appendChild(first); var nav = document.getElementById('nav'); var loadLinks = function(element, hyphen, level) { var e = element; if (e) { var children = e.children; for(var i = 0; i < e.children.length; ++i) { var currentLink = children[i];
identifier_body
get_unique.py
""" get_unique.py USAGE: get_unique.py [-h] [--sarcastic_path SARCASTIC_PATH] [--non_sarcastic_path NON_SARCASTIC_PATH] Create one json file with unique tweets optional arguments: -h, --help show this help message and exit --sarcastic_path path to directory of sarcastic tweet jsons. Needs trailing "/" --non_sarcastic_path path to directory of non sarcastic tweet jsons. Needs trailing "/" """ import glob import json import os import argparse from json_io import list_to_json, list_from_json if __name__ == "__main__": # Setup CLA parser parser = argparse.ArgumentParser(description='Create one json file with unique tweets') parser.add_argument('--sarcastic_path', help='path to directory of sarcastic tweet jsons. Needs trailing "/"') parser.add_argument('--non_sarcastic_path', help='path to directory of non sarcastic tweet jsons. Needs trailing "/"') # Parse CLAs args = parser.parse_args() top_lvl_paths_lst = [] if args.sarcastic_path:
if args.non_sarcastic_path: if not os.path.exists(args.non_sarcastic_path): raise Exception("Invalid path: {}".format(args.non_sarcastic_path)) top_lvl_paths_lst.append(args.non_sarcastic_path) # set static filenames FN_HASH = "hash_dict.json" FN_UNIQUE = "unique.json" # Populate list with paths to jsons json_paths_lst = [glob.glob(p + "*-*-*_*-*-*.json") for p in top_lvl_paths_lst] # Find and save unique tweets and updated hash dict for json_paths, top_lvl_path in zip(json_paths_lst, top_lvl_paths_lst): # load in existing list of unique tweets if it exists unique_tweets_lst = [] if os.path.exists(top_lvl_path + FN_UNIQUE): unique_tweets_lst = list_from_json(top_lvl_path + FN_UNIQUE) # load in existing hash dict if it exists hash_dict = {} if os.path.exists(top_lvl_path + FN_HASH): hash_dict = list_from_json(top_lvl_path + FN_HASH) # populate list with all tweets (possibly non-unique) for user passed directory tweets_lst = [ tweet for json_path in json_paths for tweet in list_from_json(json_path)] # for each tweet, check its existence in hash dict. Update unique list and hash dict for tweet in tweets_lst: if str(tweet['id']) not in hash_dict: unique_tweets_lst.append(tweet) hash_dict[str(tweet['id'])] = True # Save updated unique tweets list and hash dict list_to_json(unique_tweets_lst, top_lvl_path + FN_UNIQUE, old_format=False) list_to_json(hash_dict, top_lvl_path + FN_HASH)
if not os.path.exists(args.sarcastic_path): raise Exception("Invalid path: {}".format(args.sarcastic_path)) top_lvl_paths_lst.append(args.sarcastic_path)
conditional_block
get_unique.py
""" get_unique.py USAGE: get_unique.py [-h] [--sarcastic_path SARCASTIC_PATH] [--non_sarcastic_path NON_SARCASTIC_PATH] Create one json file with unique tweets optional arguments: -h, --help show this help message and exit --sarcastic_path path to directory of sarcastic tweet jsons. Needs
--non_sarcastic_path path to directory of non sarcastic tweet jsons. Needs trailing "/" """ import glob import json import os import argparse from json_io import list_to_json, list_from_json if __name__ == "__main__": # Setup CLA parser parser = argparse.ArgumentParser(description='Create one json file with unique tweets') parser.add_argument('--sarcastic_path', help='path to directory of sarcastic tweet jsons. Needs trailing "/"') parser.add_argument('--non_sarcastic_path', help='path to directory of non sarcastic tweet jsons. Needs trailing "/"') # Parse CLAs args = parser.parse_args() top_lvl_paths_lst = [] if args.sarcastic_path: if not os.path.exists(args.sarcastic_path): raise Exception("Invalid path: {}".format(args.sarcastic_path)) top_lvl_paths_lst.append(args.sarcastic_path) if args.non_sarcastic_path: if not os.path.exists(args.non_sarcastic_path): raise Exception("Invalid path: {}".format(args.non_sarcastic_path)) top_lvl_paths_lst.append(args.non_sarcastic_path) # set static filenames FN_HASH = "hash_dict.json" FN_UNIQUE = "unique.json" # Populate list with paths to jsons json_paths_lst = [glob.glob(p + "*-*-*_*-*-*.json") for p in top_lvl_paths_lst] # Find and save unique tweets and updated hash dict for json_paths, top_lvl_path in zip(json_paths_lst, top_lvl_paths_lst): # load in existing list of unique tweets if it exists unique_tweets_lst = [] if os.path.exists(top_lvl_path + FN_UNIQUE): unique_tweets_lst = list_from_json(top_lvl_path + FN_UNIQUE) # load in existing hash dict if it exists hash_dict = {} if os.path.exists(top_lvl_path + FN_HASH): hash_dict = list_from_json(top_lvl_path + FN_HASH) # populate list with all tweets (possibly non-unique) for user passed directory tweets_lst = [ tweet for json_path in json_paths for tweet in list_from_json(json_path)] # for each tweet, check its existence in hash dict. Update unique list and hash dict for tweet in tweets_lst: if str(tweet['id']) not in hash_dict: unique_tweets_lst.append(tweet) hash_dict[str(tweet['id'])] = True # Save updated unique tweets list and hash dict list_to_json(unique_tweets_lst, top_lvl_path + FN_UNIQUE, old_format=False) list_to_json(hash_dict, top_lvl_path + FN_HASH)
trailing "/"
random_line_split
mail.py
# # Sending emails in combination # with Motion surveillance software # # (c) Dr. Yves J. Hilpisch # The Python Quants GmbH # import smtplib from datetime import datetime from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText def prompt(prompt):
fromaddr = '[email protected]' # prompt("From: ") toaddrs = '[email protected]' # prompt("To: ") subject = 'Security Alert.' # prompt("Subject: ") msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddrs msg['Subject'] = subject # Add the From: and To: headers at the start! # msg = ("From: %s\r\nTo: %s\r\n\r\nSubject: %s\r\n" # % (fromaddr, ", ".join(toaddrs), subject)) # print "Enter message, end with ^D (Unix) or ^Z (Windows):" # body = '' #while 1: # try: # line = raw_input() # except EOFError: # break # if not line: # break # body = body + line body = 'A motion has been detected.\nTime: %s' % str(datetime.now()) msg.attach(MIMEText(body, 'plain')) print "Message length is " + repr(len(msg)) smtp = smtplib.SMTP() # smtp.starttls() smtp.set_debuglevel(1) smtp.connect('smtp.hilpisch.com', 587) smtp.login('hilpisch13', 'henrynikolaus06') text = msg.as_string() smtp.sendmail(fromaddr, toaddrs, text) smtp.quit() print text
return raw_input(prompt).strip()
identifier_body
mail.py
# # Sending emails in combination # with Motion surveillance software # # (c) Dr. Yves J. Hilpisch # The Python Quants GmbH # import smtplib from datetime import datetime from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText def
(prompt): return raw_input(prompt).strip() fromaddr = '[email protected]' # prompt("From: ") toaddrs = '[email protected]' # prompt("To: ") subject = 'Security Alert.' # prompt("Subject: ") msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddrs msg['Subject'] = subject # Add the From: and To: headers at the start! # msg = ("From: %s\r\nTo: %s\r\n\r\nSubject: %s\r\n" # % (fromaddr, ", ".join(toaddrs), subject)) # print "Enter message, end with ^D (Unix) or ^Z (Windows):" # body = '' #while 1: # try: # line = raw_input() # except EOFError: # break # if not line: # break # body = body + line body = 'A motion has been detected.\nTime: %s' % str(datetime.now()) msg.attach(MIMEText(body, 'plain')) print "Message length is " + repr(len(msg)) smtp = smtplib.SMTP() # smtp.starttls() smtp.set_debuglevel(1) smtp.connect('smtp.hilpisch.com', 587) smtp.login('hilpisch13', 'henrynikolaus06') text = msg.as_string() smtp.sendmail(fromaddr, toaddrs, text) smtp.quit() print text
prompt
identifier_name
mail.py
# # Sending emails in combination # with Motion surveillance software # # (c) Dr. Yves J. Hilpisch # The Python Quants GmbH # import smtplib from datetime import datetime from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText def prompt(prompt): return raw_input(prompt).strip() fromaddr = '[email protected]' # prompt("From: ") toaddrs = '[email protected]' # prompt("To: ") subject = 'Security Alert.' # prompt("Subject: ") msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddrs msg['Subject'] = subject # Add the From: and To: headers at the start! # msg = ("From: %s\r\nTo: %s\r\n\r\nSubject: %s\r\n" # % (fromaddr, ", ".join(toaddrs), subject)) # print "Enter message, end with ^D (Unix) or ^Z (Windows):" # body = '' #while 1: # try: # line = raw_input() # except EOFError: # break # if not line: # break # body = body + line body = 'A motion has been detected.\nTime: %s' % str(datetime.now()) msg.attach(MIMEText(body, 'plain')) print "Message length is " + repr(len(msg)) smtp = smtplib.SMTP() # smtp.starttls() smtp.set_debuglevel(1) smtp.connect('smtp.hilpisch.com', 587) smtp.login('hilpisch13', 'henrynikolaus06') text = msg.as_string() smtp.sendmail(fromaddr, toaddrs, text) smtp.quit()
print text
random_line_split
twitter.js
social.addModule("twitter", null, { name: "twitter", oauth: { version: '1.0', authorize_uri: 'api.twitter.com/oauth/authorize', reg_oauth_token: /oauth_token=([^&]+)(?:&oauth_verifier=([^&]+))?/, request_token_uri: 'api.twitter.com/oauth/request_token', access_token_uri: 'api.twitter.com/oauth/access_token', reg_request_token: /oauth_token=([^&]+)(?:&oauth_callback_confirmed=(.*))?/, access_token_uri: 'api.twitter.com/oauth/access_token', reg_access_token: /oauth_token=([^&]+)(?:&oauth_token_secret=([^&]+))(?:&user_id=([^&]+))(?:&screen_name=([^&]+))?/, consumer_key: 'EcWebn9hDOHy613YIR53rw', consumer_secret: '0Mqepe07PJ5j8cFHA8IbnJigBYUYppn5z882xpIGOo', signature_method: 'HMAC-SHA1', callback_url: 'https://twitter.com/robots.txt', oauth_token: null, oauth_token_secret: null }, parser: { }, api: { verify_credential: function(includeEntities, skipStatus){ return { method: "GET", url: "https://api.twitter.com/1.1/account/verify_credentials.json", data_merge: { include_entities: includeEntities | false, skip_status: skipStatus | true }, scope: true }; }, user: function(userId, screenName, includeEntities){ return{ method: "GET", url: "https://api.twitter.com/1.1/users/show.json", data_merge: { user_id: userId,
scope: true }; }, me: function(){ return this.verify_credential(true, false); } } });
screen_name: screenName, include_entities: includeEntities || false },
random_line_split
password_based_encryption.rs
1 3ae8a89d dcf8e3cb 41fdc130 \ b2329dbe 07d6f4d3 2c34e050 c8bd7e93 3b12", }) } #[test] fn one_byte() { test_vector(TestVector { password: "thepassword", encryption_salt: "0001020304050607", hmac_salt: "0102030405060708", iv: "02030405060708090a0b0c0d0e0f0001", plain_text: "01", cipher_text: "03010001 02030405 06070102 03040506 07080203 04050607 08090a0b 0c0d0e0f \ 0001a1f8 730e0bf4 80eb7b70 f690abf2 1e029514 164ad3c4 74a51b30 c7eaa1ca \ 545b7de3 de5b010a cbad0a9a 13857df6 96a8", }) } #[test] fn exactly_one_block() { test_vector(TestVector { password: "thepassword", encryption_salt: "0102030405060700", hmac_salt: "0203040506070801", iv: "030405060708090a0b0c0d0e0f000102", plain_text: "0123456789abcdef", cipher_text: "03010102 03040506 07000203 04050607 08010304 05060708 090a0b0c 0d0e0f00 \ 01020e43 7fe80930 9c03fd53 a475131e 9a1978b8 eaef576f 60adb8ce 2320849b \ a32d7429 00438ba8 97d22210 c76c35c8 49df", }) }
encryption_salt: "0203040506070001", hmac_salt: "0304050607080102", iv: "0405060708090a0b0c0d0e0f00010203", plain_text: "0123456789abcdef 01234567", cipher_text: "03010203 04050607 00010304 05060708 01020405 06070809 0a0b0c0d 0e0f0001 \ 0203e01b bda5df2c a8adace3 8f6c588d 291e03f9 51b78d34 17bc2816 581dc6b7 \ 67f1a2e5 7597512b 18e1638f 21235fa5 928c", }) } #[test] fn multibyte_password() { test_vector(TestVector { password: "中文密码", encryption_salt: "0304050607000102", hmac_salt: "0405060708010203", iv: "05060708090a0b0c0d0e0f0001020304", plain_text: "23456789abcdef 0123456701", cipher_text: "03010304 05060700 01020405 06070801 02030506 0708090a 0b0c0d0e 0f000102 \ 03048a9e 08bdec1c 4bfe13e8 1fb85f00 9ab3ddb9 1387e809 c4ad86d9 e8a60145 \ 57716657 bd317d4b b6a76446 15b3de40 2341", }) } #[test] fn longer_text_and_password() { test_vector(TestVector { password: "It was the best of times, it was the worst of times; it was the age of wisdom, \ it was the age of foolishness;", encryption_salt: "0405060700010203", hmac_salt: "0506070801020304", iv: "060708090a0b0c0d0e0f000102030405", plain_text: "69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 62 65 6c 69 65 \ 66 2c 20 69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 69 6e \ 63 72 65 64 75 6c 69 74 79 3b 20 69 74 20 77 61 73 20 74 68 65 20 73 65 61 \ 73 6f 6e 20 6f 66 20 4c 69 67 68 74 2c 20 69 74 20 77 61 73 20 74 68 65 20 \ 73 65 61 73 6f 6e 20 6f 66 20 44 61 72 6b 6e 65 73 73 3b 20 69 74 20 77 61 \ 73 20 74 68 65 20 73 70 72 69 6e 67 20 6f 66 20 68 6f 70 65 2c 20 69 74 20 \ 77 61 73 20 74 68 65 20 77 69 6e 74 65 72 20 6f 66 20 64 65 73 70 61 69 72 \ 3b 20 77 65 20 68 61 64 20 65 76 65 72 79 74 68 69 6e 67 20 62 65 66 6f 72 \ 65
#[test] fn more_than_one_block() { test_vector(TestVector { password: "thepassword",
random_line_split
password_based_encryption.rs
{ password: &'static str, encryption_salt: &'static str, hmac_salt: &'static str, iv: &'static str, plain_text: &'static str, cipher_text: &'static str, } fn test_vector(vector: TestVector) { let encryption_salt = Salt(vector.encryption_salt.from_hex().unwrap()); let hmac_salt = Salt(vector.hmac_salt.from_hex().unwrap()); let iv = IV::from(vector.iv.from_hex().unwrap()); let plain_text = vector.plain_text.from_hex().unwrap(); let ciphertext = vector.cipher_text.from_hex().unwrap(); let result = Encryptor::from_password(vector.password, encryption_salt, hmac_salt, iv) .and_then(|e| e.encrypt(&plain_text)); match result { Err(e) => panic!(e), Ok(encrypted) => assert_eq!(*encrypted.as_slice(), *ciphertext.as_slice()), } } #[test] fn all_fields_empty_or_zero() { test_vector(TestVector { password: "a", encryption_salt: "0000000000000000", hmac_salt: "0000000000000000", iv: "00000000000000000000000000000000", plain_text: "", cipher_text: "03010000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 \ 0000b303 9be31cd7 ece5e754 f5c8da17 00366631 3ae8a89d dcf8e3cb 41fdc130 \ b2329dbe 07d6f4d3 2c34e050 c8bd7e93 3b12", }) } #[test] fn one_byte() { test_vector(TestVector { password: "thepassword", encryption_salt: "0001020304050607", hmac_salt: "0102030405060708", iv: "02030405060708090a0b0c0d0e0f0001", plain_text: "01", cipher_text: "03010001 02030405 06070102 03040506 07080203 04050607 08090a0b 0c0d0e0f \ 0001a1f8 730e0bf4 80eb7b70 f690abf2 1e029514 164ad3c4 74a51b30 c7eaa1ca \ 545b7de3 de5b010a cbad0a9a 13857df6 96a8", }) } #[test] fn exactly_one_block() { test_vector(TestVector { password: "thepassword", encryption_salt: "0102030405060700", hmac_salt: "0203040506070801", iv: "030405060708090a0b0c0d0e0f000102", plain_text: "0123456789abcdef", cipher_text: "03010102 03040506 07000203 04050607 08010304 05060708 090a0b0c 0d0e0f00 \ 01020e43 7fe80930 9c03fd53 a475131e 9a1978b8 eaef576f 60adb8ce 2320849b \ a32d7429 00438ba8 97d22210 c76c35c8 49df", }) } #[test] fn more_than_one_block() { test_vector(TestVector { password: "thepassword", encryption_salt: "0203040506070001", hmac_salt: "0304050607080102", iv: "0405060708090a0b0c0d0e0f00010203", plain_text: "0123456789abcdef 01234567", cipher_text: "03010203 04050607 00010304 05060708 01020405 06070809 0a0b0c0d 0e0f0001 \ 0203e01b bda5df2c a8adace3 8f6c588d 291e03f9 51b78d34 17bc2816 581dc6b7 \ 67f1a2e5 7597512b 18e1638f 21235fa5 928c", }) } #[test] fn multibyte_password() { test_vector(TestVector { password: "中文密码", encryption_salt: "0304050607000102", hmac_salt: "0405060708010203", iv: "05060708090a0b0c0d0e0f0001020304", plain_text: "23456789abcdef 0123456701", cipher_text: "03010304 05060700 01020405 06070801 02030506 0708090a 0b0c0d0e 0f000102 \ 03048a9e 08bdec1c 4bfe13e8 1fb85f00 9ab3ddb9 1387e809 c4ad86d9 e8a60145 \ 57716657 bd317d4b b6a76446 15b3de40 2341", }) } #[test] fn longer_text_and_password() { test_vector(TestVector { password: "It was the best of times, it was the worst of times; it was the age of wisdom, \ it was the age of foolishness;", encryption_salt: "0405060700010203", hmac_salt: "0506070801020304", iv: "060708090a0b0c0d0e0f000102030405", plain_text: "69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 62 65 6c 69 65 \ 66 2c 20 69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 69 6e \ 63 72 65 64 75 6c 69 74 79 3b 20 69 74 2
TestVector
identifier_name
password_based_encryption.rs
3ae8a89d dcf8e3cb 41fdc130 \ b2329dbe 07d6f4d3 2c34e050 c8bd7e93 3b12", }) } #[test] fn one_byte() { test_vector(TestVector { password: "thepassword", encryption_salt: "0001020304050607", hmac_salt: "0102030405060708", iv: "02030405060708090a0b0c0d0e0f0001", plain_text: "01", cipher_text: "03010001 02030405 06070102 03040506 07080203 04050607 08090a0b 0c0d0e0f \ 0001a1f8 730e0bf4 80eb7b70 f690abf2 1e029514 164ad3c4 74a51b30 c7eaa1ca \ 545b7de3 de5b010a cbad0a9a 13857df6 96a8", }) } #[test] fn exactly_one_block() { test_vector(TestVector { password: "thepassword", encryption_salt: "0102030405060700", hmac_salt: "0203040506070801", iv: "030405060708090a0b0c0d0e0f000102", plain_text: "0123456789abcdef", cipher_text: "03010102 03040506 07000203 04050607 08010304 05060708 090a0b0c 0d0e0f00 \ 01020e43 7fe80930 9c03fd53 a475131e 9a1978b8 eaef576f 60adb8ce 2320849b \ a32d7429 00438ba8 97d22210 c76c35c8 49df", }) } #[test] fn more_than_one_block()
#[test] fn multibyte_password() { test_vector(TestVector { password: "中文密码", encryption_salt: "0304050607000102", hmac_salt: "0405060708010203", iv: "05060708090a0b0c0d0e0f0001020304", plain_text: "23456789abcdef 0123456701", cipher_text: "03010304 05060700 01020405 06070801 02030506 0708090a 0b0c0d0e 0f000102 \ 03048a9e 08bdec1c 4bfe13e8 1fb85f00 9ab3ddb9 1387e809 c4ad86d9 e8a60145 \ 57716657 bd317d4b b6a76446 15b3de40 2341", }) } #[test] fn longer_text_and_password() { test_vector(TestVector { password: "It was the best of times, it was the worst of times; it was the age of wisdom, \ it was the age of foolishness;", encryption_salt: "0405060700010203", hmac_salt: "0506070801020304", iv: "060708090a0b0c0d0e0f000102030405", plain_text: "69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 62 65 6c 69 65 \ 66 2c 20 69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 69 6e \ 63 72 65 64 75 6c 69 74 79 3b 20 69 74 20 77 61 73 20 74 68 65 20 73 65 61 \ 73 6f 6e 20 6f 66 20 4c 69 67 68 74 2c 20 69 74 20 77 61 73 20 74 68 65 20 \ 73 65 61 73 6f 6e 20 6f 66 20 44 61 72 6b 6e 65 73 73 3b 20 69 74 20 77 61 \ 73 20 74 68 65 20 73 70 72 69 6e 67 20 6f 66 20 68 6f 70 65 2c 20 69 74 20 \ 77 61 73 20 74 68 65 20 77 69 6e 74 65 72 20 6f 66 20 64 65 73 70 61 69 72 \ 3b 20 77 65 20 68 61 64 20 65 76 65 72 79 74 68 69 6e 67 20 62 65 66 6f 72 \ 6
{ test_vector(TestVector { password: "thepassword", encryption_salt: "0203040506070001", hmac_salt: "0304050607080102", iv: "0405060708090a0b0c0d0e0f00010203", plain_text: "0123456789abcdef 01234567", cipher_text: "03010203 04050607 00010304 05060708 01020405 06070809 0a0b0c0d 0e0f0001 \ 0203e01b bda5df2c a8adace3 8f6c588d 291e03f9 51b78d34 17bc2816 581dc6b7 \ 67f1a2e5 7597512b 18e1638f 21235fa5 928c", }) }
identifier_body
trait-bounds-sugar.rs
// Copyright 2013 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. // Tests for "default" bounds inferred for traits with no bounds list. trait Foo {} fn
(_x: Box<Foo+Send>) { } fn b(_x: &'static Foo) { // should be same as &'static Foo+'static } fn c(x: Box<Foo+Share>) { a(x); //~ ERROR expected bounds `Send` } fn d(x: &'static Foo+Share) { b(x); //~ ERROR expected bounds `'static` } fn main() {}
a
identifier_name
trait-bounds-sugar.rs
// Copyright 2013 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. // Tests for "default" bounds inferred for traits with no bounds list.
fn b(_x: &'static Foo) { // should be same as &'static Foo+'static } fn c(x: Box<Foo+Share>) { a(x); //~ ERROR expected bounds `Send` } fn d(x: &'static Foo+Share) { b(x); //~ ERROR expected bounds `'static` } fn main() {}
trait Foo {} fn a(_x: Box<Foo+Send>) { }
random_line_split
trait-bounds-sugar.rs
// Copyright 2013 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. // Tests for "default" bounds inferred for traits with no bounds list. trait Foo {} fn a(_x: Box<Foo+Send>) { } fn b(_x: &'static Foo) { // should be same as &'static Foo+'static } fn c(x: Box<Foo+Share>)
fn d(x: &'static Foo+Share) { b(x); //~ ERROR expected bounds `'static` } fn main() {}
{ a(x); //~ ERROR expected bounds `Send` }
identifier_body
controller-v2.ts
import { v4 as uuid } from "uuid"; import axios from "axios"; import Brakes from "brakes"; const stripeChargeUrl = "http://localhost:8099/charge"; const brake = new Brakes(chargeCreditCard, { timeout: 150 }); // /api/payment/v2 export const routev2 = async (_, res) => { const traceId = uuid(); const customerId = "0815"; const amount = 15; brake .exec({ customerId, amount, traceId }) .then(() => res.json({ status: "completed", traceId })) .catch(e => res.status(503).json({ error: e.message })); }; async function chargeCreditCard({ amount, customerId, traceId })
{ const response = await axios.post(stripeChargeUrl, { amount, customerId, traceId }); return response.data.transactionId; }
identifier_body
controller-v2.ts
import { v4 as uuid } from "uuid"; import axios from "axios"; import Brakes from "brakes"; const stripeChargeUrl = "http://localhost:8099/charge"; const brake = new Brakes(chargeCreditCard, { timeout: 150 }); // /api/payment/v2 export const routev2 = async (_, res) => { const traceId = uuid(); const customerId = "0815"; const amount = 15; brake .exec({ customerId, amount, traceId }) .then(() => res.json({ status: "completed", traceId })) .catch(e => res.status(503).json({ error: e.message })); }; async function
({ amount, customerId, traceId }) { const response = await axios.post(stripeChargeUrl, { amount, customerId, traceId }); return response.data.transactionId; }
chargeCreditCard
identifier_name
controller-v2.ts
import { v4 as uuid } from "uuid"; import axios from "axios";
timeout: 150 }); // /api/payment/v2 export const routev2 = async (_, res) => { const traceId = uuid(); const customerId = "0815"; const amount = 15; brake .exec({ customerId, amount, traceId }) .then(() => res.json({ status: "completed", traceId })) .catch(e => res.status(503).json({ error: e.message })); }; async function chargeCreditCard({ amount, customerId, traceId }) { const response = await axios.post(stripeChargeUrl, { amount, customerId, traceId }); return response.data.transactionId; }
import Brakes from "brakes"; const stripeChargeUrl = "http://localhost:8099/charge"; const brake = new Brakes(chargeCreditCard, {
random_line_split
Attachment.ts
/****************************************************************************** * Spine Runtimes Software License * Version 2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ namespace pixi_spine.core { export abstract class Attachment { name: string; constructor(name: string) { if (name == null) throw new Error("name cannot be null."); this.name = name; } } export abstract class VertexAttachment extends Attachment { bones: Array<number>; vertices: ArrayLike<number>; worldVerticesLength = 0; constructor(name: string) { super(name); } computeWorldVertices(slot: Slot, worldVertices: ArrayLike<number>) { this.computeWorldVerticesWith(slot, 0, this.worldVerticesLength, worldVertices, 0); } /** Transforms local vertices to world coordinates. * @param start The index of the first local vertex value to transform. Each vertex has 2 values, x and y. * @param count The number of world vertex values to output. Must be <= {@link #getWorldVerticesLength()} - start. * @param worldVertices The output world vertices. Must have a length >= offset + count. * @param offset The worldVertices index to begin writing values. */ computeWorldVerticesWith(slot: Slot, start: number, count: number, worldVertices: ArrayLike<number>, offset: number) { count += offset; let skeleton = slot.bone.skeleton; let deformArray = slot.attachmentVertices; let vertices = this.vertices; let bones = this.bones; if (bones == null) { if (deformArray.length > 0) vertices = deformArray; let bone = slot.bone; let m = bone.matrix; let x = m.tx; let y = m.ty; let a = m.a, b = m.c, c = m.b, d = m.d; for (let v = start, w = offset; w < count; v += 2, w += 2) { let vx = vertices[v], vy = vertices[v + 1]; worldVertices[w] = vx * a + vy * b + x; worldVertices[w + 1] = vx * c + vy * d + y; } return; } let v = 0, skip = 0; for (let i = 0; i < start; i += 2) { let n = bones[v]; v += n + 1; skip += n; } let skeletonBones = skeleton.bones; if (deformArray.length == 0) { for (let w = offset, b = skip * 3; w < count; w += 2) { let wx = 0, wy = 0; let n = bones[v++]; n += v; for (; v < n; v++, b += 3) { let bone = skeletonBones[bones[v]]; let m = bone.matrix; let vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; wx += (vx * m.a + vy * m.c + m.tx) * weight; wy += (vx * m.b + vy * m.d + m.ty) * weight; } worldVertices[w] = wx; worldVertices[w + 1] = wy; } } else { let deform = deformArray; for (let w = offset, b = skip * 3, f = skip << 1; w < count; w += 2) { let wx = 0, wy = 0; let n = bones[v++]; n += v; for (; v < n; v++, b += 3, f += 2) { let bone = skeletonBones[bones[v]]; let m = bone.matrix; let vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2]; wx += (vx * m.a + vy * m.c + m.tx) * weight; wy += (vx * m.b + vy * m.d + m.ty) * weight; } worldVertices[w] = wx; worldVertices[w + 1] = wy; } } } /** Returns true if a deform originally applied to the specified attachment should be applied to this attachment. */ applyDeform(sourceAttachment: VertexAttachment)
} }
{ return this == sourceAttachment; }
identifier_body
Attachment.ts
/****************************************************************************** * Spine Runtimes Software License * Version 2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ namespace pixi_spine.core { export abstract class Attachment { name: string; constructor(name: string) { if (name == null) throw new Error("name cannot be null."); this.name = name; } } export abstract class VertexAttachment extends Attachment { bones: Array<number>; vertices: ArrayLike<number>; worldVerticesLength = 0; constructor(name: string) { super(name); } computeWorldVertices(slot: Slot, worldVertices: ArrayLike<number>) { this.computeWorldVerticesWith(slot, 0, this.worldVerticesLength, worldVertices, 0); } /** Transforms local vertices to world coordinates. * @param start The index of the first local vertex value to transform. Each vertex has 2 values, x and y. * @param count The number of world vertex values to output. Must be <= {@link #getWorldVerticesLength()} - start. * @param worldVertices The output world vertices. Must have a length >= offset + count. * @param offset The worldVertices index to begin writing values. */ computeWorldVerticesWith(slot: Slot, start: number, count: number, worldVertices: ArrayLike<number>, offset: number) { count += offset; let skeleton = slot.bone.skeleton; let deformArray = slot.attachmentVertices; let vertices = this.vertices; let bones = this.bones; if (bones == null) { if (deformArray.length > 0) vertices = deformArray; let bone = slot.bone; let m = bone.matrix; let x = m.tx; let y = m.ty; let a = m.a, b = m.c, c = m.b, d = m.d; for (let v = start, w = offset; w < count; v += 2, w += 2) { let vx = vertices[v], vy = vertices[v + 1]; worldVertices[w] = vx * a + vy * b + x; worldVertices[w + 1] = vx * c + vy * d + y; } return; } let v = 0, skip = 0; for (let i = 0; i < start; i += 2) { let n = bones[v]; v += n + 1; skip += n; } let skeletonBones = skeleton.bones; if (deformArray.length == 0) { for (let w = offset, b = skip * 3; w < count; w += 2) { let wx = 0, wy = 0; let n = bones[v++]; n += v; for (; v < n; v++, b += 3) { let bone = skeletonBones[bones[v]]; let m = bone.matrix; let vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; wx += (vx * m.a + vy * m.c + m.tx) * weight; wy += (vx * m.b + vy * m.d + m.ty) * weight; } worldVertices[w] = wx; worldVertices[w + 1] = wy; } } else { let deform = deformArray; for (let w = offset, b = skip * 3, f = skip << 1; w < count; w += 2) { let wx = 0, wy = 0; let n = bones[v++]; n += v; for (; v < n; v++, b += 3, f += 2) { let bone = skeletonBones[bones[v]]; let m = bone.matrix; let vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2]; wx += (vx * m.a + vy * m.c + m.tx) * weight; wy += (vx * m.b + vy * m.d + m.ty) * weight; } worldVertices[w] = wx; worldVertices[w + 1] = wy; } } } /** Returns true if a deform originally applied to the specified attachment should be applied to this attachment. */ applyDeform(sourceAttachment: VertexAttachment) { return this == sourceAttachment; } } }
random_line_split
Attachment.ts
/****************************************************************************** * Spine Runtimes Software License * Version 2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ namespace pixi_spine.core { export abstract class Attachment { name: string; constructor(name: string) { if (name == null) throw new Error("name cannot be null."); this.name = name; } } export abstract class VertexAttachment extends Attachment { bones: Array<number>; vertices: ArrayLike<number>; worldVerticesLength = 0; constructor(name: string) { super(name); } computeWorldVertices(slot: Slot, worldVertices: ArrayLike<number>) { this.computeWorldVerticesWith(slot, 0, this.worldVerticesLength, worldVertices, 0); } /** Transforms local vertices to world coordinates. * @param start The index of the first local vertex value to transform. Each vertex has 2 values, x and y. * @param count The number of world vertex values to output. Must be <= {@link #getWorldVerticesLength()} - start. * @param worldVertices The output world vertices. Must have a length >= offset + count. * @param offset The worldVertices index to begin writing values. */
(slot: Slot, start: number, count: number, worldVertices: ArrayLike<number>, offset: number) { count += offset; let skeleton = slot.bone.skeleton; let deformArray = slot.attachmentVertices; let vertices = this.vertices; let bones = this.bones; if (bones == null) { if (deformArray.length > 0) vertices = deformArray; let bone = slot.bone; let m = bone.matrix; let x = m.tx; let y = m.ty; let a = m.a, b = m.c, c = m.b, d = m.d; for (let v = start, w = offset; w < count; v += 2, w += 2) { let vx = vertices[v], vy = vertices[v + 1]; worldVertices[w] = vx * a + vy * b + x; worldVertices[w + 1] = vx * c + vy * d + y; } return; } let v = 0, skip = 0; for (let i = 0; i < start; i += 2) { let n = bones[v]; v += n + 1; skip += n; } let skeletonBones = skeleton.bones; if (deformArray.length == 0) { for (let w = offset, b = skip * 3; w < count; w += 2) { let wx = 0, wy = 0; let n = bones[v++]; n += v; for (; v < n; v++, b += 3) { let bone = skeletonBones[bones[v]]; let m = bone.matrix; let vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; wx += (vx * m.a + vy * m.c + m.tx) * weight; wy += (vx * m.b + vy * m.d + m.ty) * weight; } worldVertices[w] = wx; worldVertices[w + 1] = wy; } } else { let deform = deformArray; for (let w = offset, b = skip * 3, f = skip << 1; w < count; w += 2) { let wx = 0, wy = 0; let n = bones[v++]; n += v; for (; v < n; v++, b += 3, f += 2) { let bone = skeletonBones[bones[v]]; let m = bone.matrix; let vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2]; wx += (vx * m.a + vy * m.c + m.tx) * weight; wy += (vx * m.b + vy * m.d + m.ty) * weight; } worldVertices[w] = wx; worldVertices[w + 1] = wy; } } } /** Returns true if a deform originally applied to the specified attachment should be applied to this attachment. */ applyDeform(sourceAttachment: VertexAttachment) { return this == sourceAttachment; } } }
computeWorldVerticesWith
identifier_name
index.js
static get propTypes() { return { data: React.PropTypes.array.isRequired, width: React.PropTypes.number, height: React.PropTypes.number, xType: React.PropTypes.string, yType: React.PropTypes.string, datePattern: React.PropTypes.string, interpolate: React.PropTypes.string, style: React.PropTypes.object, margin: React.PropTypes.object, axes: React.PropTypes.bool, grid: React.PropTypes.bool, verticalGrid: React.PropTypes.bool, xDomainRange: React.PropTypes.array, yDomainRange: React.PropTypes.array, tickTimeDisplayFormat: React.PropTypes.string, yTicks: React.PropTypes.number, xTicks: React.PropTypes.number, dataPoints: React.PropTypes.bool, lineColors: React.PropTypes.array, axisLabels: React.PropTypes.shape({ x: React.PropTypes.string, y: React.PropTypes.string }), yAxisOrientRight: React.PropTypes.bool, mouseOverHandler: React.PropTypes.func, mouseOutHandler: React.PropTypes.func, mouseMoveHandler: React.PropTypes.func, clickHandler: React.PropTypes.func }; } static get defaultProps() { return { width: 200, height: 150, datePattern: '%d-%b-%y', interpolate: 'linear', axes: false, xType: 'linear', yType: 'linear', lineColors: [], axisLabels: { x: '', y: '' }, mouseOverHandler: () => {}, mouseOutHandler: () => {}, mouseMoveHandler: () => {}, clickHandler: () => {} }; } constructor(props) { super(props); this.uid = createUniqueID(props); } componentDidMount() { const lineChart = this.refs.lineChart; createCircularTicks(lineChart); } componentDidUpdate() { const lineChart = this.refs.lineChart; createCircularTicks(lineChart); } createSvgNode({ m, w, h }) { const node = createElement('svg'); node.setAttribute('width', w + m.left + m.right); node.setAttribute('height', h + m.top + m.bottom); return node; } createSvgRoot({ node, m }) { return select(node) .append('g') .attr('transform', `translate(${m.left}, ${m.top})`); } createXAxis({ root, m, w, h, x }) { const { xType, axisLabels: { x: label }, xTicks, grid, verticalGrid, tickTimeDisplayFormat, yAxisOrientRight } = this.props; const axis = svg.axis() .scale(x) .orient('bottom'); if (xType === 'time' && tickTimeDisplayFormat) { axis .tickFormat(time.format(tickTimeDisplayFormat)); } if (grid && verticalGrid) { axis .tickSize(-h, 6) .tickPadding(15); } else { axis .tickSize(0) .tickPadding(15); } if (xTicks) { axis.ticks(xTicks); } const group = root .append('g') .attr('class', 'x axis') .attr('transform', `translate(0, ${h})`); group .call(axis); if (label) { group .append('text') .attr('class', 'label') .attr('y', m.bottom - 10) .attr('x', yAxisOrientRight ? 0 : w) .style('text-anchor', (yAxisOrientRight) ? 'start' : 'end') .text(label); } } createYAxis({ root, m, w, y }) { const { yType, axisLabels: { y: label }, yTicks, grid, tickTimeDisplayFormat, yAxisOrientRight } = this.props; const axis = svg.axis() .scale(y) .orient(yAxisOrientRight ? 'right' : 'left'); if (yType === 'time' && tickTimeDisplayFormat) { axis .tickFormat(time.format(tickTimeDisplayFormat)); } if (grid) { axis .tickSize(-w, 6) .tickPadding(12); } else
if (yTicks) { axis.ticks(yTicks); } const group = root .append('g') .attr('class', 'y axis') .attr('transform', (yAxisOrientRight) ? `translate(${w}, 0)` : 'translate(0, 0)'); group .call(axis); if (label) { group .append('text') .attr('class', 'label') .attr('transform', 'rotate(-90)') .attr('x', 0) .attr('y', (yAxisOrientRight) ? -20 + m.right : 0 - m.left) .attr('dy', '.9em') .style('text-anchor', 'end') .text(label); } } createLinePathChart({ root, x, y, xValue, yValue, colors }) { const { data, interpolate } = this.props; const getStroke = (d, i) => colors[i]; const linePath = svg.line() .interpolate(interpolate) .x((d) => x(xValue(d))) .y((d) => y(yValue(d))); const group = root .append('g') .attr('class', 'lineChart'); group .selectAll('path') .data(data) .enter() .append('path') .attr('class', 'line') .style('stroke', getStroke) .attr('d', linePath); } createPoints({ root, x, y, colors }) { const { data, xType, yType, mouseOverHandler, mouseOutHandler, mouseMoveHandler, clickHandler } = this.props; /* * We don't really need to do this, but it * avoids obscure "this" below */ const calculateDate = (v) => this.parseDate(v); const getStroke = (d, i) => colors[i]; /* * Creating the calculation functions */ const calculateCX = (d) => ( (xType === 'time') ? x(calculateDate(d.x)) : x(d.x)); const calculateCY = (d) => ( (yType === 'time') ? y(calculateDate(d.y)) : y(d.y)); const mouseover = (d) => mouseOverHandler(d, lastEvent); const mouseout = (d) => mouseOutHandler(d, lastEvent); const mousemove = (d) => mouseMoveHandler(d, lastEvent); const click = (d) => clickHandler(d, lastEvent); const group = root .append('g') .attr('class', 'dataPoints'); data.forEach((item) => { item.forEach((d) => { /* * Applying the calculation functions */ group .datum(d) .append('circle') .attr('class', 'data-point') .style('strokeWidth', '2px') .style('stroke', getStroke) .style('fill', 'white') .attr('cx', calculateCX) .attr('cy', calculateCY) .on('mouseover', mouseover) .on('mouseout', mouseout) .on('mousemove', mousemove) .on('click', click); }); }); } createStyle() { const { style, grid, verticalGrid, yAxisOrientRight } = this.props; const uid = this.uid; const scope = `.line-chart-${uid}`; const axisStyles = getAxisStyles(grid, verticalGrid, yAxisOrientRight); const rules = merge({}, defaultStyles, style, axisStyles); return ( <Style scopeSelector={scope} rules={rules} /> ); } parseDate(v) { const { datePattern } = this.props; const datePatternParser = ( dateParser[datePattern] || ( dateParser[datePattern] = parse(datePattern))); return datePatternParser(v); } calculateChartParameters() { const { data, axes, xType, yType, xDomainRange, yDomainRange, margin, width, height, lineColors, yAxisOrientRight } = this.props; /* * We could "bind"! */ const parseDate = (v) => this.parseDate(v); /* * 'w' and 'h' are the width and height of the graph canvas * (excluding axes and other furniture) */ const m = calculateMargin(axes, margin, yAxisOrientRight); const w = reduce(width, m.left, m.right); const
{ axis .tickPadding(10); }
conditional_block
index.js
static get propTypes() { return { data: React.PropTypes.array.isRequired, width: React.PropTypes.number, height: React.PropTypes.number, xType: React.PropTypes.string, yType: React.PropTypes.string, datePattern: React.PropTypes.string, interpolate: React.PropTypes.string, style: React.PropTypes.object, margin: React.PropTypes.object, axes: React.PropTypes.bool, grid: React.PropTypes.bool, verticalGrid: React.PropTypes.bool, xDomainRange: React.PropTypes.array, yDomainRange: React.PropTypes.array, tickTimeDisplayFormat: React.PropTypes.string, yTicks: React.PropTypes.number, xTicks: React.PropTypes.number, dataPoints: React.PropTypes.bool, lineColors: React.PropTypes.array, axisLabels: React.PropTypes.shape({ x: React.PropTypes.string, y: React.PropTypes.string }), yAxisOrientRight: React.PropTypes.bool, mouseOverHandler: React.PropTypes.func, mouseOutHandler: React.PropTypes.func, mouseMoveHandler: React.PropTypes.func, clickHandler: React.PropTypes.func }; } static get defaultProps() { return { width: 200, height: 150, datePattern: '%d-%b-%y', interpolate: 'linear', axes: false, xType: 'linear', yType: 'linear', lineColors: [], axisLabels: { x: '', y: '' }, mouseOverHandler: () => {}, mouseOutHandler: () => {}, mouseMoveHandler: () => {}, clickHandler: () => {} }; } constructor(props) { super(props); this.uid = createUniqueID(props); } componentDidMount() { const lineChart = this.refs.lineChart; createCircularTicks(lineChart); } componentDidUpdate() { const lineChart = this.refs.lineChart; createCircularTicks(lineChart); } createSvgNode({ m, w, h }) { const node = createElement('svg'); node.setAttribute('width', w + m.left + m.right); node.setAttribute('height', h + m.top + m.bottom); return node; } createSvgRoot({ node, m }) { return select(node) .append('g') .attr('transform', `translate(${m.left}, ${m.top})`); } createXAxis({ root, m, w, h, x }) { const { xType, axisLabels: { x: label }, xTicks, grid, verticalGrid, tickTimeDisplayFormat, yAxisOrientRight } = this.props; const axis = svg.axis() .scale(x) .orient('bottom'); if (xType === 'time' && tickTimeDisplayFormat) { axis .tickFormat(time.format(tickTimeDisplayFormat)); } if (grid && verticalGrid) { axis .tickSize(-h, 6) .tickPadding(15); } else { axis .tickSize(0) .tickPadding(15); } if (xTicks) { axis.ticks(xTicks); } const group = root .append('g') .attr('class', 'x axis') .attr('transform', `translate(0, ${h})`); group .call(axis); if (label) { group .append('text') .attr('class', 'label') .attr('y', m.bottom - 10) .attr('x', yAxisOrientRight ? 0 : w) .style('text-anchor', (yAxisOrientRight) ? 'start' : 'end') .text(label); } } createYAxis({ root, m, w, y }) { const { yType, axisLabels: { y: label }, yTicks, grid, tickTimeDisplayFormat, yAxisOrientRight } = this.props; const axis = svg.axis() .scale(y) .orient(yAxisOrientRight ? 'right' : 'left'); if (yType === 'time' && tickTimeDisplayFormat) { axis .tickFormat(time.format(tickTimeDisplayFormat)); } if (grid) { axis .tickSize(-w, 6) .tickPadding(12); } else { axis .tickPadding(10); } if (yTicks) { axis.ticks(yTicks); } const group = root .append('g') .attr('class', 'y axis') .attr('transform', (yAxisOrientRight) ? `translate(${w}, 0)` : 'translate(0, 0)'); group .call(axis); if (label) { group .append('text') .attr('class', 'label') .attr('transform', 'rotate(-90)') .attr('x', 0) .attr('y', (yAxisOrientRight) ? -20 + m.right : 0 - m.left) .attr('dy', '.9em') .style('text-anchor', 'end') .text(label); } } createLinePathChart({ root, x, y, xValue, yValue, colors }) { const { data, interpolate } = this.props; const getStroke = (d, i) => colors[i]; const linePath = svg.line() .interpolate(interpolate) .x((d) => x(xValue(d))) .y((d) => y(yValue(d))); const group = root .append('g') .attr('class', 'lineChart'); group .selectAll('path') .data(data) .enter() .append('path') .attr('class', 'line') .style('stroke', getStroke) .attr('d', linePath); }
createPoints({ root, x, y, colors }) { const { data, xType, yType, mouseOverHandler, mouseOutHandler, mouseMoveHandler, clickHandler } = this.props; /* * We don't really need to do this, but it * avoids obscure "this" below */ const calculateDate = (v) => this.parseDate(v); const getStroke = (d, i) => colors[i]; /* * Creating the calculation functions */ const calculateCX = (d) => ( (xType === 'time') ? x(calculateDate(d.x)) : x(d.x)); const calculateCY = (d) => ( (yType === 'time') ? y(calculateDate(d.y)) : y(d.y)); const mouseover = (d) => mouseOverHandler(d, lastEvent); const mouseout = (d) => mouseOutHandler(d, lastEvent); const mousemove = (d) => mouseMoveHandler(d, lastEvent); const click = (d) => clickHandler(d, lastEvent); const group = root .append('g') .attr('class', 'dataPoints'); data.forEach((item) => { item.forEach((d) => { /* * Applying the calculation functions */ group .datum(d) .append('circle') .attr('class', 'data-point') .style('strokeWidth', '2px') .style('stroke', getStroke) .style('fill', 'white') .attr('cx', calculateCX) .attr('cy', calculateCY) .on('mouseover', mouseover) .on('mouseout', mouseout) .on('mousemove', mousemove) .on('click', click); }); }); } createStyle() { const { style, grid, verticalGrid, yAxisOrientRight } = this.props; const uid = this.uid; const scope = `.line-chart-${uid}`; const axisStyles = getAxisStyles(grid, verticalGrid, yAxisOrientRight); const rules = merge({}, defaultStyles, style, axisStyles); return ( <Style scopeSelector={scope} rules={rules} /> ); } parseDate(v) { const { datePattern } = this.props; const datePatternParser = ( dateParser[datePattern] || ( dateParser[datePattern] = parse(datePattern))); return datePatternParser(v); } calculateChartParameters() { const { data, axes, xType, yType, xDomainRange, yDomainRange, margin, width, height, lineColors, yAxisOrientRight } = this.props; /* * We could "bind"! */ const parseDate = (v) => this.parseDate(v); /* * 'w' and 'h' are the width and height of the graph canvas * (excluding axes and other furniture) */ const m = calculateMargin(axes, margin, yAxisOrientRight); const w = reduce(width, m.left, m.right); const h
random_line_split
index.js
static get propTypes() { return { data: React.PropTypes.array.isRequired, width: React.PropTypes.number, height: React.PropTypes.number, xType: React.PropTypes.string, yType: React.PropTypes.string, datePattern: React.PropTypes.string, interpolate: React.PropTypes.string, style: React.PropTypes.object, margin: React.PropTypes.object, axes: React.PropTypes.bool, grid: React.PropTypes.bool, verticalGrid: React.PropTypes.bool, xDomainRange: React.PropTypes.array, yDomainRange: React.PropTypes.array, tickTimeDisplayFormat: React.PropTypes.string, yTicks: React.PropTypes.number, xTicks: React.PropTypes.number, dataPoints: React.PropTypes.bool, lineColors: React.PropTypes.array, axisLabels: React.PropTypes.shape({ x: React.PropTypes.string, y: React.PropTypes.string }), yAxisOrientRight: React.PropTypes.bool, mouseOverHandler: React.PropTypes.func, mouseOutHandler: React.PropTypes.func, mouseMoveHandler: React.PropTypes.func, clickHandler: React.PropTypes.func }; } static get
() { return { width: 200, height: 150, datePattern: '%d-%b-%y', interpolate: 'linear', axes: false, xType: 'linear', yType: 'linear', lineColors: [], axisLabels: { x: '', y: '' }, mouseOverHandler: () => {}, mouseOutHandler: () => {}, mouseMoveHandler: () => {}, clickHandler: () => {} }; } constructor(props) { super(props); this.uid = createUniqueID(props); } componentDidMount() { const lineChart = this.refs.lineChart; createCircularTicks(lineChart); } componentDidUpdate() { const lineChart = this.refs.lineChart; createCircularTicks(lineChart); } createSvgNode({ m, w, h }) { const node = createElement('svg'); node.setAttribute('width', w + m.left + m.right); node.setAttribute('height', h + m.top + m.bottom); return node; } createSvgRoot({ node, m }) { return select(node) .append('g') .attr('transform', `translate(${m.left}, ${m.top})`); } createXAxis({ root, m, w, h, x }) { const { xType, axisLabels: { x: label }, xTicks, grid, verticalGrid, tickTimeDisplayFormat, yAxisOrientRight } = this.props; const axis = svg.axis() .scale(x) .orient('bottom'); if (xType === 'time' && tickTimeDisplayFormat) { axis .tickFormat(time.format(tickTimeDisplayFormat)); } if (grid && verticalGrid) { axis .tickSize(-h, 6) .tickPadding(15); } else { axis .tickSize(0) .tickPadding(15); } if (xTicks) { axis.ticks(xTicks); } const group = root .append('g') .attr('class', 'x axis') .attr('transform', `translate(0, ${h})`); group .call(axis); if (label) { group .append('text') .attr('class', 'label') .attr('y', m.bottom - 10) .attr('x', yAxisOrientRight ? 0 : w) .style('text-anchor', (yAxisOrientRight) ? 'start' : 'end') .text(label); } } createYAxis({ root, m, w, y }) { const { yType, axisLabels: { y: label }, yTicks, grid, tickTimeDisplayFormat, yAxisOrientRight } = this.props; const axis = svg.axis() .scale(y) .orient(yAxisOrientRight ? 'right' : 'left'); if (yType === 'time' && tickTimeDisplayFormat) { axis .tickFormat(time.format(tickTimeDisplayFormat)); } if (grid) { axis .tickSize(-w, 6) .tickPadding(12); } else { axis .tickPadding(10); } if (yTicks) { axis.ticks(yTicks); } const group = root .append('g') .attr('class', 'y axis') .attr('transform', (yAxisOrientRight) ? `translate(${w}, 0)` : 'translate(0, 0)'); group .call(axis); if (label) { group .append('text') .attr('class', 'label') .attr('transform', 'rotate(-90)') .attr('x', 0) .attr('y', (yAxisOrientRight) ? -20 + m.right : 0 - m.left) .attr('dy', '.9em') .style('text-anchor', 'end') .text(label); } } createLinePathChart({ root, x, y, xValue, yValue, colors }) { const { data, interpolate } = this.props; const getStroke = (d, i) => colors[i]; const linePath = svg.line() .interpolate(interpolate) .x((d) => x(xValue(d))) .y((d) => y(yValue(d))); const group = root .append('g') .attr('class', 'lineChart'); group .selectAll('path') .data(data) .enter() .append('path') .attr('class', 'line') .style('stroke', getStroke) .attr('d', linePath); } createPoints({ root, x, y, colors }) { const { data, xType, yType, mouseOverHandler, mouseOutHandler, mouseMoveHandler, clickHandler } = this.props; /* * We don't really need to do this, but it * avoids obscure "this" below */ const calculateDate = (v) => this.parseDate(v); const getStroke = (d, i) => colors[i]; /* * Creating the calculation functions */ const calculateCX = (d) => ( (xType === 'time') ? x(calculateDate(d.x)) : x(d.x)); const calculateCY = (d) => ( (yType === 'time') ? y(calculateDate(d.y)) : y(d.y)); const mouseover = (d) => mouseOverHandler(d, lastEvent); const mouseout = (d) => mouseOutHandler(d, lastEvent); const mousemove = (d) => mouseMoveHandler(d, lastEvent); const click = (d) => clickHandler(d, lastEvent); const group = root .append('g') .attr('class', 'dataPoints'); data.forEach((item) => { item.forEach((d) => { /* * Applying the calculation functions */ group .datum(d) .append('circle') .attr('class', 'data-point') .style('strokeWidth', '2px') .style('stroke', getStroke) .style('fill', 'white') .attr('cx', calculateCX) .attr('cy', calculateCY) .on('mouseover', mouseover) .on('mouseout', mouseout) .on('mousemove', mousemove) .on('click', click); }); }); } createStyle() { const { style, grid, verticalGrid, yAxisOrientRight } = this.props; const uid = this.uid; const scope = `.line-chart-${uid}`; const axisStyles = getAxisStyles(grid, verticalGrid, yAxisOrientRight); const rules = merge({}, defaultStyles, style, axisStyles); return ( <Style scopeSelector={scope} rules={rules} /> ); } parseDate(v) { const { datePattern } = this.props; const datePatternParser = ( dateParser[datePattern] || ( dateParser[datePattern] = parse(datePattern))); return datePatternParser(v); } calculateChartParameters() { const { data, axes, xType, yType, xDomainRange, yDomainRange, margin, width, height, lineColors, yAxisOrientRight } = this.props; /* * We could "bind"! */ const parseDate = (v) => this.parseDate(v); /* * 'w' and 'h' are the width and height of the graph canvas * (excluding axes and other furniture) */ const m = calculateMargin(axes, margin, yAxisOrientRight); const w = reduce(width, m.left, m.right); const
defaultProps
identifier_name
index.js
static get propTypes() { return { data: React.PropTypes.array.isRequired, width: React.PropTypes.number, height: React.PropTypes.number, xType: React.PropTypes.string, yType: React.PropTypes.string, datePattern: React.PropTypes.string, interpolate: React.PropTypes.string, style: React.PropTypes.object, margin: React.PropTypes.object, axes: React.PropTypes.bool, grid: React.PropTypes.bool, verticalGrid: React.PropTypes.bool, xDomainRange: React.PropTypes.array, yDomainRange: React.PropTypes.array, tickTimeDisplayFormat: React.PropTypes.string, yTicks: React.PropTypes.number, xTicks: React.PropTypes.number, dataPoints: React.PropTypes.bool, lineColors: React.PropTypes.array, axisLabels: React.PropTypes.shape({ x: React.PropTypes.string, y: React.PropTypes.string }), yAxisOrientRight: React.PropTypes.bool, mouseOverHandler: React.PropTypes.func, mouseOutHandler: React.PropTypes.func, mouseMoveHandler: React.PropTypes.func, clickHandler: React.PropTypes.func }; } static get defaultProps() { return { width: 200, height: 150, datePattern: '%d-%b-%y', interpolate: 'linear', axes: false, xType: 'linear', yType: 'linear', lineColors: [], axisLabels: { x: '', y: '' }, mouseOverHandler: () => {}, mouseOutHandler: () => {}, mouseMoveHandler: () => {}, clickHandler: () => {} }; } constructor(props) { super(props); this.uid = createUniqueID(props); } componentDidMount() { const lineChart = this.refs.lineChart; createCircularTicks(lineChart); } componentDidUpdate() { const lineChart = this.refs.lineChart; createCircularTicks(lineChart); } createSvgNode({ m, w, h }) { const node = createElement('svg'); node.setAttribute('width', w + m.left + m.right); node.setAttribute('height', h + m.top + m.bottom); return node; } createSvgRoot({ node, m }) { return select(node) .append('g') .attr('transform', `translate(${m.left}, ${m.top})`); } createXAxis({ root, m, w, h, x }) { const { xType, axisLabels: { x: label }, xTicks, grid, verticalGrid, tickTimeDisplayFormat, yAxisOrientRight } = this.props; const axis = svg.axis() .scale(x) .orient('bottom'); if (xType === 'time' && tickTimeDisplayFormat) { axis .tickFormat(time.format(tickTimeDisplayFormat)); } if (grid && verticalGrid) { axis .tickSize(-h, 6) .tickPadding(15); } else { axis .tickSize(0) .tickPadding(15); } if (xTicks) { axis.ticks(xTicks); } const group = root .append('g') .attr('class', 'x axis') .attr('transform', `translate(0, ${h})`); group .call(axis); if (label) { group .append('text') .attr('class', 'label') .attr('y', m.bottom - 10) .attr('x', yAxisOrientRight ? 0 : w) .style('text-anchor', (yAxisOrientRight) ? 'start' : 'end') .text(label); } } createYAxis({ root, m, w, y }) { const { yType, axisLabels: { y: label }, yTicks, grid, tickTimeDisplayFormat, yAxisOrientRight } = this.props; const axis = svg.axis() .scale(y) .orient(yAxisOrientRight ? 'right' : 'left'); if (yType === 'time' && tickTimeDisplayFormat) { axis .tickFormat(time.format(tickTimeDisplayFormat)); } if (grid) { axis .tickSize(-w, 6) .tickPadding(12); } else { axis .tickPadding(10); } if (yTicks) { axis.ticks(yTicks); } const group = root .append('g') .attr('class', 'y axis') .attr('transform', (yAxisOrientRight) ? `translate(${w}, 0)` : 'translate(0, 0)'); group .call(axis); if (label) { group .append('text') .attr('class', 'label') .attr('transform', 'rotate(-90)') .attr('x', 0) .attr('y', (yAxisOrientRight) ? -20 + m.right : 0 - m.left) .attr('dy', '.9em') .style('text-anchor', 'end') .text(label); } } createLinePathChart({ root, x, y, xValue, yValue, colors }) { const { data, interpolate } = this.props; const getStroke = (d, i) => colors[i]; const linePath = svg.line() .interpolate(interpolate) .x((d) => x(xValue(d))) .y((d) => y(yValue(d))); const group = root .append('g') .attr('class', 'lineChart'); group .selectAll('path') .data(data) .enter() .append('path') .attr('class', 'line') .style('stroke', getStroke) .attr('d', linePath); } createPoints({ root, x, y, colors })
* Creating the calculation functions */ const calculateCX = (d) => ( (xType === 'time') ? x(calculateDate(d.x)) : x(d.x)); const calculateCY = (d) => ( (yType === 'time') ? y(calculateDate(d.y)) : y(d.y)); const mouseover = (d) => mouseOverHandler(d, lastEvent); const mouseout = (d) => mouseOutHandler(d, lastEvent); const mousemove = (d) => mouseMoveHandler(d, lastEvent); const click = (d) => clickHandler(d, lastEvent); const group = root .append('g') .attr('class', 'dataPoints'); data.forEach((item) => { item.forEach((d) => { /* * Applying the calculation functions */ group .datum(d) .append('circle') .attr('class', 'data-point') .style('strokeWidth', '2px') .style('stroke', getStroke) .style('fill', 'white') .attr('cx', calculateCX) .attr('cy', calculateCY) .on('mouseover', mouseover) .on('mouseout', mouseout) .on('mousemove', mousemove) .on('click', click); }); }); } createStyle() { const { style, grid, verticalGrid, yAxisOrientRight } = this.props; const uid = this.uid; const scope = `.line-chart-${uid}`; const axisStyles = getAxisStyles(grid, verticalGrid, yAxisOrientRight); const rules = merge({}, defaultStyles, style, axisStyles); return ( <Style scopeSelector={scope} rules={rules} /> ); } parseDate(v) { const { datePattern } = this.props; const datePatternParser = ( dateParser[datePattern] || ( dateParser[datePattern] = parse(datePattern))); return datePatternParser(v); } calculateChartParameters() { const { data, axes, xType, yType, xDomainRange, yDomainRange, margin, width, height, lineColors, yAxisOrientRight } = this.props; /* * We could "bind"! */ const parseDate = (v) => this.parseDate(v); /* * 'w' and 'h' are the width and height of the graph canvas * (excluding axes and other furniture) */ const m = calculateMargin(axes, margin, yAxisOrientRight); const w = reduce(width, m.left, m.right); const h
{ const { data, xType, yType, mouseOverHandler, mouseOutHandler, mouseMoveHandler, clickHandler } = this.props; /* * We don't really need to do this, but it * avoids obscure "this" below */ const calculateDate = (v) => this.parseDate(v); const getStroke = (d, i) => colors[i]; /*
identifier_body
B_Frame.py
from DemoFramework import DemoFramework from LUIVerticalLayout import LUIVerticalLayout from LUIFrame import LUIFrame from LUILabel import LUILabel from LUIButton import LUIButton from LUIObject import LUIObject import random f = DemoFramework() f.prepare_demo("LUIFrame")
# Constructor f.add_constructor_parameter("width", "200") f.add_constructor_parameter("height", "200") f.add_constructor_parameter("innerPadding", "5") f.add_constructor_parameter("scrollable", "False") f.add_constructor_parameter("style", "UIFrame.Raised") # Functions # Events f.construct_sourcecode("LUIFrame") # Construct a new frame frame = LUIFrame(parent=f.get_widget_node()) layout = LUIVerticalLayout(parent=frame, spacing=5) layout.add(LUILabel(text="This is some frame ..", color=(0.2, 0.6, 1.0, 1.0), font_size=20)) layout.add(LUILabel(text="It can contain arbitrary elements.")) layout.add(LUILabel(text="For example this button:")) layout.add(LUIButton(text="Fancy button")) # frame.fit_to_children() f.set_actions({ "Resize to 300x160": lambda: frame.set_size(300, 160), "Fit to children": lambda: frame.clear_size(), }) run()
random_line_split
action.js
/** * @author Krzysztof Winiarski * @copyright (c) 2014 Krzysztof Winiarski * @license MIT */ 'use strict'; var support = require('../support'); var actionWrapper = require('./action-wrapper'); function validateTypeOfArrayRecords(array, name, type) { if (!array || !array instanceof Array) { throw new TypeError('ResourceAction(config.' + name + ') needs to be an Array'); } else
} function validateAction(config) { if (!config.id || typeof config.id !== 'string' && config.id.length > 0) { throw new TypeError('ResourceAction(config.id) needs to be a non empty string'); } if (!config.handler || typeof config.handler !== 'function') { throw new TypeError('ResourceAction(config.handler) needs to be a function'); } if (!config.mountPath) { throw new TypeError('ResourceAction(config.mountPath) is missing'); } else { if (config.mountPath instanceof Array) { validateTypeOfArrayRecords(config.mountPath, 'mountPath', 'string'); } } validateTypeOfArrayRecords(config.policies, 'policies', 'function'); validateTypeOfArrayRecords(config.methods, 'methods', 'string'); } /** * ResourceAction represents single action for selected resource. For example * POST /resource/mount-path/action-path. Action must have handler function * (from blueprints or user defined, eventually 404 NotImplemented error handler). * Additionally ResourceAction may have policies registered. * @param handler * @constructor */ function ResourceAction(handler) { if (!handler || typeof handler !== 'function') { throw new TypeError('ResourceAction(handler) needs to be a function'); } for (var key in handler) { if (handler[key]) { this[key] = handler[key]; } } if (!this.mountPath) { this.mountPath = '/' + support.camelCaseToDash(this.id); } this.handler = actionWrapper(handler); validateAction(this); } ResourceAction.prototype.policies = []; ResourceAction.prototype.methods = ['GET']; /** * * @param {Object} policies */ ResourceAction.prototype.registerPolicies = function(policies) { this.policies = this.policies.concat(policies); }; module.exports = ResourceAction;
{ for (var i = 0, j = array.length; i < j; i++) { if (typeof array[i] !== type) { throw new TypeError('ResourceAction(config.' + name + '[' + i + ']) needs to be a ' + type); } } }
conditional_block
action.js
/** * @author Krzysztof Winiarski * @copyright (c) 2014 Krzysztof Winiarski * @license MIT */ 'use strict'; var support = require('../support'); var actionWrapper = require('./action-wrapper'); function validateTypeOfArrayRecords(array, name, type)
function validateAction(config) { if (!config.id || typeof config.id !== 'string' && config.id.length > 0) { throw new TypeError('ResourceAction(config.id) needs to be a non empty string'); } if (!config.handler || typeof config.handler !== 'function') { throw new TypeError('ResourceAction(config.handler) needs to be a function'); } if (!config.mountPath) { throw new TypeError('ResourceAction(config.mountPath) is missing'); } else { if (config.mountPath instanceof Array) { validateTypeOfArrayRecords(config.mountPath, 'mountPath', 'string'); } } validateTypeOfArrayRecords(config.policies, 'policies', 'function'); validateTypeOfArrayRecords(config.methods, 'methods', 'string'); } /** * ResourceAction represents single action for selected resource. For example * POST /resource/mount-path/action-path. Action must have handler function * (from blueprints or user defined, eventually 404 NotImplemented error handler). * Additionally ResourceAction may have policies registered. * @param handler * @constructor */ function ResourceAction(handler) { if (!handler || typeof handler !== 'function') { throw new TypeError('ResourceAction(handler) needs to be a function'); } for (var key in handler) { if (handler[key]) { this[key] = handler[key]; } } if (!this.mountPath) { this.mountPath = '/' + support.camelCaseToDash(this.id); } this.handler = actionWrapper(handler); validateAction(this); } ResourceAction.prototype.policies = []; ResourceAction.prototype.methods = ['GET']; /** * * @param {Object} policies */ ResourceAction.prototype.registerPolicies = function(policies) { this.policies = this.policies.concat(policies); }; module.exports = ResourceAction;
{ if (!array || !array instanceof Array) { throw new TypeError('ResourceAction(config.' + name + ') needs to be an Array'); } else { for (var i = 0, j = array.length; i < j; i++) { if (typeof array[i] !== type) { throw new TypeError('ResourceAction(config.' + name + '[' + i + ']) needs to be a ' + type); } } } }
identifier_body
action.js
/** * @author Krzysztof Winiarski * @copyright (c) 2014 Krzysztof Winiarski * @license MIT */ 'use strict'; var support = require('../support'); var actionWrapper = require('./action-wrapper'); function validateTypeOfArrayRecords(array, name, type) { if (!array || !array instanceof Array) { throw new TypeError('ResourceAction(config.' + name + ') needs to be an Array'); } else { for (var i = 0, j = array.length; i < j; i++) { if (typeof array[i] !== type) { throw new TypeError('ResourceAction(config.' + name + '[' + i + ']) needs to be a ' + type); } } } } function validateAction(config) { if (!config.id || typeof config.id !== 'string' && config.id.length > 0) { throw new TypeError('ResourceAction(config.id) needs to be a non empty string'); } if (!config.handler || typeof config.handler !== 'function') { throw new TypeError('ResourceAction(config.handler) needs to be a function'); } if (!config.mountPath) { throw new TypeError('ResourceAction(config.mountPath) is missing'); } else { if (config.mountPath instanceof Array) { validateTypeOfArrayRecords(config.mountPath, 'mountPath', 'string'); } } validateTypeOfArrayRecords(config.policies, 'policies', 'function'); validateTypeOfArrayRecords(config.methods, 'methods', 'string'); } /**
* ResourceAction represents single action for selected resource. For example * POST /resource/mount-path/action-path. Action must have handler function * (from blueprints or user defined, eventually 404 NotImplemented error handler). * Additionally ResourceAction may have policies registered. * @param handler * @constructor */ function ResourceAction(handler) { if (!handler || typeof handler !== 'function') { throw new TypeError('ResourceAction(handler) needs to be a function'); } for (var key in handler) { if (handler[key]) { this[key] = handler[key]; } } if (!this.mountPath) { this.mountPath = '/' + support.camelCaseToDash(this.id); } this.handler = actionWrapper(handler); validateAction(this); } ResourceAction.prototype.policies = []; ResourceAction.prototype.methods = ['GET']; /** * * @param {Object} policies */ ResourceAction.prototype.registerPolicies = function(policies) { this.policies = this.policies.concat(policies); }; module.exports = ResourceAction;
random_line_split
action.js
/** * @author Krzysztof Winiarski * @copyright (c) 2014 Krzysztof Winiarski * @license MIT */ 'use strict'; var support = require('../support'); var actionWrapper = require('./action-wrapper'); function
(array, name, type) { if (!array || !array instanceof Array) { throw new TypeError('ResourceAction(config.' + name + ') needs to be an Array'); } else { for (var i = 0, j = array.length; i < j; i++) { if (typeof array[i] !== type) { throw new TypeError('ResourceAction(config.' + name + '[' + i + ']) needs to be a ' + type); } } } } function validateAction(config) { if (!config.id || typeof config.id !== 'string' && config.id.length > 0) { throw new TypeError('ResourceAction(config.id) needs to be a non empty string'); } if (!config.handler || typeof config.handler !== 'function') { throw new TypeError('ResourceAction(config.handler) needs to be a function'); } if (!config.mountPath) { throw new TypeError('ResourceAction(config.mountPath) is missing'); } else { if (config.mountPath instanceof Array) { validateTypeOfArrayRecords(config.mountPath, 'mountPath', 'string'); } } validateTypeOfArrayRecords(config.policies, 'policies', 'function'); validateTypeOfArrayRecords(config.methods, 'methods', 'string'); } /** * ResourceAction represents single action for selected resource. For example * POST /resource/mount-path/action-path. Action must have handler function * (from blueprints or user defined, eventually 404 NotImplemented error handler). * Additionally ResourceAction may have policies registered. * @param handler * @constructor */ function ResourceAction(handler) { if (!handler || typeof handler !== 'function') { throw new TypeError('ResourceAction(handler) needs to be a function'); } for (var key in handler) { if (handler[key]) { this[key] = handler[key]; } } if (!this.mountPath) { this.mountPath = '/' + support.camelCaseToDash(this.id); } this.handler = actionWrapper(handler); validateAction(this); } ResourceAction.prototype.policies = []; ResourceAction.prototype.methods = ['GET']; /** * * @param {Object} policies */ ResourceAction.prototype.registerPolicies = function(policies) { this.policies = this.policies.concat(policies); }; module.exports = ResourceAction;
validateTypeOfArrayRecords
identifier_name
const-int-saturating-arith.rs
// run-pass const INT_U32_NO: u32 = (42 as u32).saturating_add(2); const INT_U32: u32 = u32::MAX.saturating_add(1); const INT_U128: u128 = u128::MAX.saturating_add(1);
const INT_I128: i128 = i128::MAX.saturating_add(1); const INT_I128_NEG: i128 = i128::MIN.saturating_add(-1); const INT_U32_NO_SUB: u32 = (42 as u32).saturating_sub(2); const INT_U32_SUB: u32 = (1 as u32).saturating_sub(2); const INT_I32_NO_SUB: i32 = (-42 as i32).saturating_sub(2); const INT_I32_NEG_SUB: i32 = i32::MIN.saturating_sub(1); const INT_I32_POS_SUB: i32 = i32::MAX.saturating_sub(-1); const INT_U128_SUB: u128 = (0 as u128).saturating_sub(1); const INT_I128_NEG_SUB: i128 = i128::MIN.saturating_sub(1); const INT_I128_POS_SUB: i128 = i128::MAX.saturating_sub(-1); fn main() { assert_eq!(INT_U32_NO, 44); assert_eq!(INT_U32, u32::MAX); assert_eq!(INT_U128, u128::MAX); assert_eq!(INT_I128, i128::MAX); assert_eq!(INT_I128_NEG, i128::MIN); assert_eq!(INT_U32_NO_SUB, 40); assert_eq!(INT_U32_SUB, 0); assert_eq!(INT_I32_NO_SUB, -44); assert_eq!(INT_I32_NEG_SUB, i32::MIN); assert_eq!(INT_I32_POS_SUB, i32::MAX); assert_eq!(INT_U128_SUB, 0); assert_eq!(INT_I128_NEG_SUB, i128::MIN); assert_eq!(INT_I128_POS_SUB, i128::MAX); }
random_line_split
const-int-saturating-arith.rs
// run-pass const INT_U32_NO: u32 = (42 as u32).saturating_add(2); const INT_U32: u32 = u32::MAX.saturating_add(1); const INT_U128: u128 = u128::MAX.saturating_add(1); const INT_I128: i128 = i128::MAX.saturating_add(1); const INT_I128_NEG: i128 = i128::MIN.saturating_add(-1); const INT_U32_NO_SUB: u32 = (42 as u32).saturating_sub(2); const INT_U32_SUB: u32 = (1 as u32).saturating_sub(2); const INT_I32_NO_SUB: i32 = (-42 as i32).saturating_sub(2); const INT_I32_NEG_SUB: i32 = i32::MIN.saturating_sub(1); const INT_I32_POS_SUB: i32 = i32::MAX.saturating_sub(-1); const INT_U128_SUB: u128 = (0 as u128).saturating_sub(1); const INT_I128_NEG_SUB: i128 = i128::MIN.saturating_sub(1); const INT_I128_POS_SUB: i128 = i128::MAX.saturating_sub(-1); fn main()
{ assert_eq!(INT_U32_NO, 44); assert_eq!(INT_U32, u32::MAX); assert_eq!(INT_U128, u128::MAX); assert_eq!(INT_I128, i128::MAX); assert_eq!(INT_I128_NEG, i128::MIN); assert_eq!(INT_U32_NO_SUB, 40); assert_eq!(INT_U32_SUB, 0); assert_eq!(INT_I32_NO_SUB, -44); assert_eq!(INT_I32_NEG_SUB, i32::MIN); assert_eq!(INT_I32_POS_SUB, i32::MAX); assert_eq!(INT_U128_SUB, 0); assert_eq!(INT_I128_NEG_SUB, i128::MIN); assert_eq!(INT_I128_POS_SUB, i128::MAX); }
identifier_body
const-int-saturating-arith.rs
// run-pass const INT_U32_NO: u32 = (42 as u32).saturating_add(2); const INT_U32: u32 = u32::MAX.saturating_add(1); const INT_U128: u128 = u128::MAX.saturating_add(1); const INT_I128: i128 = i128::MAX.saturating_add(1); const INT_I128_NEG: i128 = i128::MIN.saturating_add(-1); const INT_U32_NO_SUB: u32 = (42 as u32).saturating_sub(2); const INT_U32_SUB: u32 = (1 as u32).saturating_sub(2); const INT_I32_NO_SUB: i32 = (-42 as i32).saturating_sub(2); const INT_I32_NEG_SUB: i32 = i32::MIN.saturating_sub(1); const INT_I32_POS_SUB: i32 = i32::MAX.saturating_sub(-1); const INT_U128_SUB: u128 = (0 as u128).saturating_sub(1); const INT_I128_NEG_SUB: i128 = i128::MIN.saturating_sub(1); const INT_I128_POS_SUB: i128 = i128::MAX.saturating_sub(-1); fn
() { assert_eq!(INT_U32_NO, 44); assert_eq!(INT_U32, u32::MAX); assert_eq!(INT_U128, u128::MAX); assert_eq!(INT_I128, i128::MAX); assert_eq!(INT_I128_NEG, i128::MIN); assert_eq!(INT_U32_NO_SUB, 40); assert_eq!(INT_U32_SUB, 0); assert_eq!(INT_I32_NO_SUB, -44); assert_eq!(INT_I32_NEG_SUB, i32::MIN); assert_eq!(INT_I32_POS_SUB, i32::MAX); assert_eq!(INT_U128_SUB, 0); assert_eq!(INT_I128_NEG_SUB, i128::MIN); assert_eq!(INT_I128_POS_SUB, i128::MAX); }
main
identifier_name
mod.rs
//! Seat handling and managing. use std::cell::RefCell; use std::rc::Rc; use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1; use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPointerConstraintsV1; use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3; use sctk::reexports::client::protocol::wl_seat::WlSeat; use sctk::reexports::client::Attached; use sctk::environment::Environment; use sctk::reexports::calloop::LoopHandle; use sctk::seat::pointer::ThemeManager; use sctk::seat::{SeatData, SeatListener}; use super::env::WinitEnv; use super::event_loop::WinitState; use crate::event::ModifiersState; mod keyboard; pub mod pointer; pub mod text_input; mod touch; use keyboard::Keyboard; use pointer::Pointers; use text_input::TextInput; use touch::Touch; pub struct SeatManager { /// Listener for seats. _seat_listener: SeatListener, } impl SeatManager { pub fn new( env: &Environment<WinitEnv>, loop_handle: LoopHandle<WinitState>, theme_manager: ThemeManager, ) -> Self { let relative_pointer_manager = env.get_global::<ZwpRelativePointerManagerV1>(); let pointer_constraints = env.get_global::<ZwpPointerConstraintsV1>(); let text_input_manager = env.get_global::<ZwpTextInputManagerV3>(); let mut inner = SeatManagerInner::new( theme_manager, relative_pointer_manager, pointer_constraints, text_input_manager, loop_handle, ); // Handle existing seats. for seat in env.get_all_seats() { let seat_data = match sctk::seat::clone_seat_data(&seat) { Some(seat_data) => seat_data, None => continue, }; inner.process_seat_update(&seat, &seat_data); } let seat_listener = env.listen_for_seats(move |seat, seat_data, _| { inner.process_seat_update(&seat, &seat_data); }); Self { _seat_listener: seat_listener, } } } /// Inner state of the seat manager. struct SeatManagerInner { /// Currently observed seats. seats: Vec<SeatInfo>, /// Loop handle. loop_handle: LoopHandle<WinitState>, /// Relative pointer manager. relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, /// Pointer constraints. pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, /// Text input manager. text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, /// A theme manager. theme_manager: ThemeManager, } impl SeatManagerInner { fn new( theme_manager: ThemeManager, relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, loop_handle: LoopHandle<WinitState>, ) -> Self { Self { seats: Vec::new(), loop_handle, relative_pointer_manager, pointer_constraints, text_input_manager, theme_manager, } } /// Handle seats update from the `SeatListener`. pub fn process_seat_update(&mut self, seat: &Attached<WlSeat>, seat_data: &SeatData) { let detached_seat = seat.detach(); let position = self.seats.iter().position(|si| si.seat == detached_seat); let index = position.unwrap_or_else(|| { self.seats.push(SeatInfo::new(detached_seat)); self.seats.len() - 1 }); let seat_info = &mut self.seats[index]; // Pointer handling. if seat_data.has_pointer && !seat_data.defunct { if seat_info.pointer.is_none() { seat_info.pointer = Some(Pointers::new( &seat, &self.theme_manager, &self.relative_pointer_manager, &self.pointer_constraints, seat_info.modifiers_state.clone(), )); } } else { seat_info.pointer = None; } // Handle keyboard. if seat_data.has_keyboard && !seat_data.defunct { if seat_info.keyboard.is_none() { seat_info.keyboard = Keyboard::new( &seat, self.loop_handle.clone(), seat_info.modifiers_state.clone(), ); } } else { seat_info.keyboard = None; } // Handle touch. if seat_data.has_touch && !seat_data.defunct { if seat_info.touch.is_none() { seat_info.touch = Some(Touch::new(&seat)); } } else { seat_info.touch = None; }
if let Some(text_input_manager) = self.text_input_manager.as_ref() { if seat_data.defunct { seat_info.text_input = None; } else if seat_info.text_input.is_none() { seat_info.text_input = Some(TextInput::new(&seat, &text_input_manager)); } } } } /// Resources associtated with a given seat. struct SeatInfo { /// Seat to which this `SeatInfo` belongs. seat: WlSeat, /// A keyboard handle with its repeat rate handling. keyboard: Option<Keyboard>, /// All pointers we're using on a seat. pointer: Option<Pointers>, /// Touch handling. touch: Option<Touch>, /// Text input handling aka IME. text_input: Option<TextInput>, /// The current state of modifiers observed in keyboard handler. /// /// We keep modifiers state on a seat, since it's being used by pointer events as well. modifiers_state: Rc<RefCell<ModifiersState>>, } impl SeatInfo { pub fn new(seat: WlSeat) -> Self { Self { seat, keyboard: None, pointer: None, touch: None, text_input: None, modifiers_state: Rc::new(RefCell::new(ModifiersState::default())), } } }
// Handle text input.
random_line_split
mod.rs
//! Seat handling and managing. use std::cell::RefCell; use std::rc::Rc; use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1; use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPointerConstraintsV1; use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3; use sctk::reexports::client::protocol::wl_seat::WlSeat; use sctk::reexports::client::Attached; use sctk::environment::Environment; use sctk::reexports::calloop::LoopHandle; use sctk::seat::pointer::ThemeManager; use sctk::seat::{SeatData, SeatListener}; use super::env::WinitEnv; use super::event_loop::WinitState; use crate::event::ModifiersState; mod keyboard; pub mod pointer; pub mod text_input; mod touch; use keyboard::Keyboard; use pointer::Pointers; use text_input::TextInput; use touch::Touch; pub struct SeatManager { /// Listener for seats. _seat_listener: SeatListener, } impl SeatManager { pub fn new( env: &Environment<WinitEnv>, loop_handle: LoopHandle<WinitState>, theme_manager: ThemeManager, ) -> Self { let relative_pointer_manager = env.get_global::<ZwpRelativePointerManagerV1>(); let pointer_constraints = env.get_global::<ZwpPointerConstraintsV1>(); let text_input_manager = env.get_global::<ZwpTextInputManagerV3>(); let mut inner = SeatManagerInner::new( theme_manager, relative_pointer_manager, pointer_constraints, text_input_manager, loop_handle, ); // Handle existing seats. for seat in env.get_all_seats() { let seat_data = match sctk::seat::clone_seat_data(&seat) { Some(seat_data) => seat_data, None => continue, }; inner.process_seat_update(&seat, &seat_data); } let seat_listener = env.listen_for_seats(move |seat, seat_data, _| { inner.process_seat_update(&seat, &seat_data); }); Self { _seat_listener: seat_listener, } } } /// Inner state of the seat manager. struct SeatManagerInner { /// Currently observed seats. seats: Vec<SeatInfo>, /// Loop handle. loop_handle: LoopHandle<WinitState>, /// Relative pointer manager. relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, /// Pointer constraints. pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, /// Text input manager. text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, /// A theme manager. theme_manager: ThemeManager, } impl SeatManagerInner { fn new( theme_manager: ThemeManager, relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, loop_handle: LoopHandle<WinitState>, ) -> Self { Self { seats: Vec::new(), loop_handle, relative_pointer_manager, pointer_constraints, text_input_manager, theme_manager, } } /// Handle seats update from the `SeatListener`. pub fn process_seat_update(&mut self, seat: &Attached<WlSeat>, seat_data: &SeatData) { let detached_seat = seat.detach(); let position = self.seats.iter().position(|si| si.seat == detached_seat); let index = position.unwrap_or_else(|| { self.seats.push(SeatInfo::new(detached_seat)); self.seats.len() - 1 }); let seat_info = &mut self.seats[index]; // Pointer handling. if seat_data.has_pointer && !seat_data.defunct { if seat_info.pointer.is_none() { seat_info.pointer = Some(Pointers::new( &seat, &self.theme_manager, &self.relative_pointer_manager, &self.pointer_constraints, seat_info.modifiers_state.clone(), )); } } else { seat_info.pointer = None; } // Handle keyboard. if seat_data.has_keyboard && !seat_data.defunct
else { seat_info.keyboard = None; } // Handle touch. if seat_data.has_touch && !seat_data.defunct { if seat_info.touch.is_none() { seat_info.touch = Some(Touch::new(&seat)); } } else { seat_info.touch = None; } // Handle text input. if let Some(text_input_manager) = self.text_input_manager.as_ref() { if seat_data.defunct { seat_info.text_input = None; } else if seat_info.text_input.is_none() { seat_info.text_input = Some(TextInput::new(&seat, &text_input_manager)); } } } } /// Resources associtated with a given seat. struct SeatInfo { /// Seat to which this `SeatInfo` belongs. seat: WlSeat, /// A keyboard handle with its repeat rate handling. keyboard: Option<Keyboard>, /// All pointers we're using on a seat. pointer: Option<Pointers>, /// Touch handling. touch: Option<Touch>, /// Text input handling aka IME. text_input: Option<TextInput>, /// The current state of modifiers observed in keyboard handler. /// /// We keep modifiers state on a seat, since it's being used by pointer events as well. modifiers_state: Rc<RefCell<ModifiersState>>, } impl SeatInfo { pub fn new(seat: WlSeat) -> Self { Self { seat, keyboard: None, pointer: None, touch: None, text_input: None, modifiers_state: Rc::new(RefCell::new(ModifiersState::default())), } } }
{ if seat_info.keyboard.is_none() { seat_info.keyboard = Keyboard::new( &seat, self.loop_handle.clone(), seat_info.modifiers_state.clone(), ); } }
conditional_block
mod.rs
//! Seat handling and managing. use std::cell::RefCell; use std::rc::Rc; use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1; use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPointerConstraintsV1; use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3; use sctk::reexports::client::protocol::wl_seat::WlSeat; use sctk::reexports::client::Attached; use sctk::environment::Environment; use sctk::reexports::calloop::LoopHandle; use sctk::seat::pointer::ThemeManager; use sctk::seat::{SeatData, SeatListener}; use super::env::WinitEnv; use super::event_loop::WinitState; use crate::event::ModifiersState; mod keyboard; pub mod pointer; pub mod text_input; mod touch; use keyboard::Keyboard; use pointer::Pointers; use text_input::TextInput; use touch::Touch; pub struct SeatManager { /// Listener for seats. _seat_listener: SeatListener, } impl SeatManager { pub fn new( env: &Environment<WinitEnv>, loop_handle: LoopHandle<WinitState>, theme_manager: ThemeManager, ) -> Self { let relative_pointer_manager = env.get_global::<ZwpRelativePointerManagerV1>(); let pointer_constraints = env.get_global::<ZwpPointerConstraintsV1>(); let text_input_manager = env.get_global::<ZwpTextInputManagerV3>(); let mut inner = SeatManagerInner::new( theme_manager, relative_pointer_manager, pointer_constraints, text_input_manager, loop_handle, ); // Handle existing seats. for seat in env.get_all_seats() { let seat_data = match sctk::seat::clone_seat_data(&seat) { Some(seat_data) => seat_data, None => continue, }; inner.process_seat_update(&seat, &seat_data); } let seat_listener = env.listen_for_seats(move |seat, seat_data, _| { inner.process_seat_update(&seat, &seat_data); }); Self { _seat_listener: seat_listener, } } } /// Inner state of the seat manager. struct SeatManagerInner { /// Currently observed seats. seats: Vec<SeatInfo>, /// Loop handle. loop_handle: LoopHandle<WinitState>, /// Relative pointer manager. relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, /// Pointer constraints. pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, /// Text input manager. text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, /// A theme manager. theme_manager: ThemeManager, } impl SeatManagerInner { fn new( theme_manager: ThemeManager, relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, loop_handle: LoopHandle<WinitState>, ) -> Self { Self { seats: Vec::new(), loop_handle, relative_pointer_manager, pointer_constraints, text_input_manager, theme_manager, } } /// Handle seats update from the `SeatListener`. pub fn
(&mut self, seat: &Attached<WlSeat>, seat_data: &SeatData) { let detached_seat = seat.detach(); let position = self.seats.iter().position(|si| si.seat == detached_seat); let index = position.unwrap_or_else(|| { self.seats.push(SeatInfo::new(detached_seat)); self.seats.len() - 1 }); let seat_info = &mut self.seats[index]; // Pointer handling. if seat_data.has_pointer && !seat_data.defunct { if seat_info.pointer.is_none() { seat_info.pointer = Some(Pointers::new( &seat, &self.theme_manager, &self.relative_pointer_manager, &self.pointer_constraints, seat_info.modifiers_state.clone(), )); } } else { seat_info.pointer = None; } // Handle keyboard. if seat_data.has_keyboard && !seat_data.defunct { if seat_info.keyboard.is_none() { seat_info.keyboard = Keyboard::new( &seat, self.loop_handle.clone(), seat_info.modifiers_state.clone(), ); } } else { seat_info.keyboard = None; } // Handle touch. if seat_data.has_touch && !seat_data.defunct { if seat_info.touch.is_none() { seat_info.touch = Some(Touch::new(&seat)); } } else { seat_info.touch = None; } // Handle text input. if let Some(text_input_manager) = self.text_input_manager.as_ref() { if seat_data.defunct { seat_info.text_input = None; } else if seat_info.text_input.is_none() { seat_info.text_input = Some(TextInput::new(&seat, &text_input_manager)); } } } } /// Resources associtated with a given seat. struct SeatInfo { /// Seat to which this `SeatInfo` belongs. seat: WlSeat, /// A keyboard handle with its repeat rate handling. keyboard: Option<Keyboard>, /// All pointers we're using on a seat. pointer: Option<Pointers>, /// Touch handling. touch: Option<Touch>, /// Text input handling aka IME. text_input: Option<TextInput>, /// The current state of modifiers observed in keyboard handler. /// /// We keep modifiers state on a seat, since it's being used by pointer events as well. modifiers_state: Rc<RefCell<ModifiersState>>, } impl SeatInfo { pub fn new(seat: WlSeat) -> Self { Self { seat, keyboard: None, pointer: None, touch: None, text_input: None, modifiers_state: Rc::new(RefCell::new(ModifiersState::default())), } } }
process_seat_update
identifier_name
folder_detector.py
import os import numpy as np import torch from ..core import FaceDetector class FolderDetector(FaceDetector): '''This is a simple helper module that assumes the faces were detected already (either previously or are provided as ground truth). The class expects to find the bounding boxes in the same format used by the rest of face detectors, mainly ``list[(x1,y1,x2,y2),...]``. For each image the detector will search for a file with the same name and with one of the following extensions: .npy, .t7 or .pth ''' def __init__(self, device, path_to_detector=None, verbose=False): super(FolderDetector, self).__init__(device, verbose) def detect_from_image(self, tensor_or_path): # Only strings supported if not isinstance(tensor_or_path, str): raise ValueError base_name = os.path.splitext(tensor_or_path)[0] if os.path.isfile(base_name + '.npy'):
elif os.path.isfile(base_name + '.t7'): detected_faces = torch.load(base_name + '.t7') elif os.path.isfile(base_name + '.pth'): detected_faces = torch.load(base_name + '.pth') else: raise FileNotFoundError if not isinstance(detected_faces, list): raise TypeError return detected_faces @property def reference_scale(self): return 195 @property def reference_x_shift(self): return 0 @property def reference_y_shift(self): return 0
detected_faces = np.load(base_name + '.npy')
conditional_block
folder_detector.py
import os import numpy as np import torch from ..core import FaceDetector class FolderDetector(FaceDetector): '''This is a simple helper module that assumes the faces were detected already (either previously or are provided as ground truth). The class expects to find the bounding boxes in the same format used by the rest of face detectors, mainly ``list[(x1,y1,x2,y2),...]``. For each image the detector will search for a file with the same name and with one of the following extensions: .npy, .t7 or .pth ''' def __init__(self, device, path_to_detector=None, verbose=False): super(FolderDetector, self).__init__(device, verbose) def detect_from_image(self, tensor_or_path): # Only strings supported if not isinstance(tensor_or_path, str): raise ValueError base_name = os.path.splitext(tensor_or_path)[0] if os.path.isfile(base_name + '.npy'): detected_faces = np.load(base_name + '.npy') elif os.path.isfile(base_name + '.t7'): detected_faces = torch.load(base_name + '.t7') elif os.path.isfile(base_name + '.pth'): detected_faces = torch.load(base_name + '.pth') else: raise FileNotFoundError if not isinstance(detected_faces, list): raise TypeError return detected_faces @property def reference_scale(self): return 195 @property def reference_x_shift(self): return 0 @property def
(self): return 0
reference_y_shift
identifier_name
folder_detector.py
import os import numpy as np import torch from ..core import FaceDetector class FolderDetector(FaceDetector): '''This is a simple helper module that assumes the faces were detected already (either previously or are provided as ground truth). The class expects to find the bounding boxes in the same format used by the rest of face detectors, mainly ``list[(x1,y1,x2,y2),...]``. For each image the detector will search for a file with the same name and with one of the following extensions: .npy, .t7 or .pth ''' def __init__(self, device, path_to_detector=None, verbose=False): super(FolderDetector, self).__init__(device, verbose) def detect_from_image(self, tensor_or_path): # Only strings supported if not isinstance(tensor_or_path, str): raise ValueError base_name = os.path.splitext(tensor_or_path)[0] if os.path.isfile(base_name + '.npy'): detected_faces = np.load(base_name + '.npy') elif os.path.isfile(base_name + '.t7'): detected_faces = torch.load(base_name + '.t7') elif os.path.isfile(base_name + '.pth'): detected_faces = torch.load(base_name + '.pth') else: raise FileNotFoundError if not isinstance(detected_faces, list): raise TypeError return detected_faces @property def reference_scale(self):
@property def reference_x_shift(self): return 0 @property def reference_y_shift(self): return 0
return 195
identifier_body
folder_detector.py
import os import numpy as np import torch from ..core import FaceDetector class FolderDetector(FaceDetector): '''This is a simple helper module that assumes the faces were detected already (either previously or are provided as ground truth). The class expects to find the bounding boxes in the same format used by the rest of face detectors, mainly ``list[(x1,y1,x2,y2),...]``. For each image the detector will search for a file with the same name and with one of the following extensions: .npy, .t7 or .pth ''' def __init__(self, device, path_to_detector=None, verbose=False): super(FolderDetector, self).__init__(device, verbose) def detect_from_image(self, tensor_or_path): # Only strings supported if not isinstance(tensor_or_path, str): raise ValueError base_name = os.path.splitext(tensor_or_path)[0] if os.path.isfile(base_name + '.npy'): detected_faces = np.load(base_name + '.npy') elif os.path.isfile(base_name + '.t7'): detected_faces = torch.load(base_name + '.t7') elif os.path.isfile(base_name + '.pth'): detected_faces = torch.load(base_name + '.pth') else: raise FileNotFoundError
return detected_faces @property def reference_scale(self): return 195 @property def reference_x_shift(self): return 0 @property def reference_y_shift(self): return 0
if not isinstance(detected_faces, list): raise TypeError
random_line_split
4_advanced.py
Examples ================= In this section, we demonstrate how to go from the inner product to the discrete approximation for some special cases. We also show how all necessary operators are constructed for each case. """ #################################################### # # Import Packages # --------------- # # Here we import the packages required for this tutorial # from discretize.utils import sdiag from discretize import TensorMesh import numpy as np
# Constitive Relations and Differential Operators # ----------------------------------------------- # # Where :math:`\psi` and :math:`\phi` are scalar quantities, # :math:`\vec{u}` and :math:`\vec{v}` are vector quantities, and # :math:`\sigma` defines a constitutive relationship, we may need to derive # discrete approximations for the following inner products: # # 1. :math:`(\vec{u} , \sigma \nabla \phi)` # 2. :math:`(\psi , \sigma \nabla \cdot \vec{v})` # 3. :math:`(\vec{u} , \sigma \nabla \times \vec{v})` # # These cases effectively combine what was learned in the previous two # tutorials. For each case, we must: # # - Define discretized quantities at the appropriate mesh locations # - Define an inner product matrix that depends on a single constitutive parameter (:math:`\sigma`) or a tensor (:math:`\Sigma`) # - Construct differential operators that may require you to define boundary conditions # # Where :math:`\mathbf{M_e}(\sigma)` is the property dependent inner-product # matrix for quantities on cell edges, :math:`\mathbf{M_f}(\sigma)` is the # property dependent inner-product matrix for quantities on cell faces, # :math:`\mathbf{G_{ne}}` is the nodes to edges gradient operator and # :math:`\mathbf{G_{cf}}` is the centers to faces gradient operator: # # .. math:: # (\vec{u} , \sigma \nabla \phi) &= \mathbf{u_f^T M_f}(\sigma) \mathbf{ G_{cf} \, \phi_c} \;\;\;\;\; (\vec{u} \;\textrm{on faces and} \; \phi \; \textrm{at centers}) \\ # &= \mathbf{u_e^T M_e}(\sigma) \mathbf{ G_{ne} \, \phi_n} \;\;\;\; (\vec{u} \;\textrm{on edges and} \; \phi \; \textrm{on nodes}) # # Where :math:`\mathbf{M_c}(\sigma)` is the property dependent inner-product # matrix for quantities at cell centers and :math:`\mathbf{D}` is the faces # to centers divergence operator: # # .. math:: # (\psi , \sigma \nabla \cdot \vec{v}) = \mathbf{\psi_c^T M_c} (\sigma)\mathbf{ D v_f} \;\;\;\; (\psi \;\textrm{at centers and} \; \vec{v} \; \textrm{on faces} ) # # Where :math:`\mathbf{C_{ef}}` is the edges to faces curl operator and # :math:`\mathbf{C_{fe}}` is the faces to edges curl operator: # # .. math:: # (\vec{u} , \sigma \nabla \times \vec{v}) &= \mathbf{u_f^T M_f} (\sigma) \mathbf{ C_{ef} \, v_e} \;\;\;\; (\vec{u} \;\textrm{on edges and} \; \vec{v} \; \textrm{on faces} )\\ # &= \mathbf{u_e^T M_e} (\sigma) \mathbf{ C_{fe} \, v_f} \;\;\;\; (\vec{u} \;\textrm{on faces and} \; \vec{v} \; \textrm{on edges} ) # # **With the operators constructed below, you can compute all of the # aforementioned inner products.** # # Make basic mesh h = np.ones(10) mesh = TensorMesh([h, h, h]) sig = np.random.rand(mesh.nC) # isotropic Sig = np.random.rand(mesh.nC, 6) # anisotropic # Inner product matricies Mc = sdiag(mesh.vol * sig) # Inner product matrix (centers) # Mn = mesh.getNodalInnerProduct(sig) # Inner product matrix (nodes) (*functionality pending*) Me = mesh.getEdgeInnerProduct(sig) # Inner product matrix (edges) Mf = mesh.getFaceInnerProduct(sig) # Inner product matrix for tensor (faces) # Differential operators Gne = mesh.nodalGrad # Nodes to edges gradient mesh.setCellGradBC(["neumann", "dirichlet", "neumann"]) # Set boundary conditions Gcf = mesh.cellGrad # Cells to faces gradient D = mesh.faceDiv # Faces to centers divergence Cef = mesh.edgeCurl # Edges to faces curl Cfe = mesh.edgeCurl.T # Faces to edges curl # EXAMPLE: (u, sig*Curl*v) fig = plt.figure(figsize=(9, 5)) ax1 = fig.add_subplot(121) ax1.spy(Mf * Cef, markersize=0.5) ax1.set_title("Me(sig)*Cef (Isotropic)", pad=10) Mf_tensor = mesh.getFaceInnerProduct(Sig) # inner product matrix for tensor ax2 = fig.add_subplot(122) ax2.spy(Mf_tensor * Cef, markersize=0.5) ax2.set_title("Me(sig)*Cef (Anisotropic)", pad=10) ##################################################### # Divergence of a Scalar and a Vector Field # ----------------------------------------- # # Where :math:`\psi` and :math:`\phi` are scalar quantities, and # :math:`\vec{u}` is a known vector field, we may need to derive # a discrete approximation for the following inner product: # # .. math:: # (\psi , \nabla \cdot \phi \vec{u}) # # Scalar and vector quantities are generally discretized to lie on # different locations on the mesh. As result, it is better to use the # identity :math:`\nabla \cdot \phi \vec{u} = \phi \nabla \cdot \vec{u} + \vec{u} \cdot \nabla \phi` # and separate the inner product into two parts: # # .. math:: # (\psi , \phi \nabla \cdot \vec{u} ) + (\psi , \vec{u} \cdot \nabla \phi) # # **Term 1:** # # If the vector field :math:`\vec{u}` is divergence free, there is no need # to evaluate the first inner product term. This is the case for advection when # the fluid is incompressible. # # Where :math:`\mathbf{D_{fc}}` is the faces to centers divergence operator, and # :math:`\mathbf{M_c}` is the basic inner product matrix for cell centered # quantities, we can approximate this inner product as: # # .. math:: # (\psi , \phi \nabla \cdot \vec{u} ) = \mathbf{\psi_c^T M_c} \textrm{diag} (\mathbf{D_{fc} u_f} ) \, \mathbf{\phi_c} # # **Term 2:** # # Let :math:`\mathbf{G_{cf}}` be the cell centers to faces gradient operator, # :math:`\mathbf{M_c}` be the basic inner product matrix for cell centered # quantities, and :math:`\mathbf{\tilde{A}_{fc}}` and averages *and* sums the # cartesian contributions of :math:`\vec{u} \cdot \nabla \phi`, we can # approximate the inner product as: # # .. math:: # (\psi , \vec{u} \cdot \nabla \phi) = \mathbf{\psi_c^T M_c \tilde A_{fc}} \text{diag} (\mathbf{u_f} ) \mathbf{G_{cf} \, \phi_c} # # **With the operators constructed below, you can compute all of the # inner products.** # Make basic mesh h = np.ones(10) mesh = TensorMesh([h, h, h]) # Inner product matricies Mc = sdiag(mesh.vol * sig) # Inner product matrix (centers) # Differential operators mesh.setCellGradBC(["neumann", "dirichlet", "neumann"]) # Set boundary conditions Gcf = mesh.cellGrad # Cells to faces gradient Dfc = mesh.faceDiv # Faces to centers divergence # Averaging and summing matrix Afc = mesh.dim *
import matplotlib.pyplot as plt #####################################################
random_line_split
dns.js
// ___ ____ __ __ // / _ `/ _ \\ \ / // \_,_/ .__/_\_\ // /_/ // // 過去は未来によって変えられる。 // // Copyright (c) 2014 Kenan Sulayman aka apx // // Based on third-party code: // // Copyright (c) 2010 Tom Hughes-Croucher // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. var dgram = require("dgram"), util = require("util"); var host = "localhost", port = process.env.port || 53; const rev = 13; var server = dgram.createSocket("udp4"); var dnx = Object.create({ records: {}, addRecord: function (domain) { this.records[domain] = { in: { a: []//, // not implemented } }; var qname = this.toolchain.utils.domainToQname(domain); return { delegate: function (r) { if ( typeof r.rdata === "string" ) { r.rdata = this.toolchain.utils.ip2dec(r.rdata); } if ( !r["qname"] ) { r["qname"] = qname; } r["zname"] = domain; if ( !this.records[domain] ) this.records[domain] = {}; if ( !this.records[domain]["in"] ) this.records[domain]["in"] = {}; if ( !this.records[domain]["in"][r.type || "a"] ) this.records[domain]["in"][r.type || "a"] = []; return this.records[domain]["in"][r.type || "a"].push(r), r; }.bind(this) }; }, server: server, toolchain: require("./lib/toolchain") }); server.on("message", function(msg, rinfo) { // parse query var q = dnx.toolchain.processRequest(msg); // build response var buf = dnx.toolchain.createResponse(q, dnx.records); dnx.server.send(buf, 0, buf.length, rinfo.port, rinfo.address); }); server.addListener("error", function(e) { throw e; }); var config = require("./config.json"); Object.keys(config).forEach(function (e) { var r = dnx.addRecord(e) config[e].forEach(function (rx) { r.delegate(rx); }) }) server.bind(port, host); console.log([ " __ ", " ___/ /__ __ __", "/ _ / _ \\\\ \\ /", "\\_,_/_//_/_\\_\\", " \t", "[dnx r" + rev + "]", "" ].join("\n")) require("dns").resolve(host, function (err, data) { var revlookup = data ? " (" + data.join(", ") + ")" : ""; console.log("Delegation:"); Object.keys(dnx.records).forEach(function (d) { console.log("\t=> ", d); Object.keys(dnx.records[d]).forEach(function (c) { Object.keys(dnx.records[d][c]).forEach(function (r) { console.log("\t\t" + c + ": " + r + ":"); dnx.records[d][c][r].forEach(function (rx) { console.log("\t\t\t", rx.qname, " (" + rx["zname"] + "): ", util.inspect(rx, {depth: null}).split("{ ").join("{\n ").split("\n").join("\n\t\t\t\t").split(" }").join("\n\t\t\t }")) }) })
});
}); }) process.stdout.write("\nStarted server: " + host + revlookup + ", using port " + port + ".");
random_line_split
models.py
from contextlib import contextmanager from datetime import datetime from django import forms from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core import validators from django.db import models from django.utils import translation from django.utils.encoding import smart_unicode from django.utils.functional import lazy import commonware.log import tower from cache_nuggets.lib import memoize from tower import ugettext as _ import amo import amo.models from amo.urlresolvers import reverse from mkt.translations.fields import NoLinksField, save_signal from mkt.translations.query import order_by_translation log = commonware.log.getLogger('z.users') class UserForeignKey(models.ForeignKey): """ A replacement for models.ForeignKey('users.UserProfile'). This field uses UserEmailField to make form fields key off the user's email instead of the primary key id. We also hook up autocomplete automatically. """ def __init__(self, *args, **kw): super(UserForeignKey, self).__init__(UserProfile, *args, **kw) def value_from_object(self, obj): return getattr(obj, self.name).email def formfield(self, **kw): defaults = {'form_class': UserEmailField} defaults.update(kw) return models.Field.formfield(self, **defaults) class UserEmailField(forms.EmailField): def clean(self, value): if value in validators.EMPTY_VALUES: raise forms.ValidationError(self.error_messages['required']) try: return UserProfile.objects.get(email=value) except UserProfile.DoesNotExist: raise forms.ValidationError(_('No user with that email.')) def widget_attrs(self, widget): lazy_reverse = lazy(reverse, str) return {'class': 'email-autocomplete', 'data-src': lazy_reverse('users.ajax')} AbstractBaseUser._meta.get_field('password').max_length = 255 class UserProfile(amo.models.OnChangeMixin, amo.models.ModelBase, AbstractBaseUser): USERNAME_FIELD = 'username' username = models.CharField(max_length=255, default='', unique=True) display_name = models.CharField(max_length=255, default='', null=True, blank=True) email = models.EmailField(unique=True, null=True) averagerating = models.CharField(max_length=255, blank=True, null=True) bio = NoLinksField(short=False) confirmationcode = models.CharField(max_length=255, default='', blank=True) deleted = models.BooleanField(default=False) display_collections = models.BooleanField(default=False) display_collections_fav = models.BooleanField(default=False) emailhidden = models.BooleanField(default=True) homepage = models.URLField(max_length=255, blank=True, default='') location = models.CharField(max_length=255, blank=True, default='') notes = models.TextField(blank=True, null=True) notifycompat = models.BooleanField(default=True) notifyevents = models.BooleanField(default=True) occupation = models.CharField(max_length=255, default='', blank=True) # This is essentially a "has_picture" flag right now picture_type = models.CharField(max_length=75, default='', blank=True) resetcode = models.CharField(max_length=255, default='', blank=True) resetcode_expires = models.DateTimeField(default=datetime.now, null=True, blank=True) read_dev_agreement = models.DateTimeField(null=True, blank=True) last_login_ip = models.CharField(default='', max_length=45, editable=False) last_login_attempt = models.DateTimeField(null=True, editable=False) last_login_attempt_ip = models.CharField(default='', max_length=45, editable=False) failed_login_attempts = models.PositiveIntegerField(default=0, editable=False) source = models.PositiveIntegerField(default=amo.LOGIN_SOURCE_UNKNOWN, editable=False, db_index=True) is_verified = models.BooleanField(default=True) region = models.CharField(max_length=11, null=True, blank=True, editable=False) lang = models.CharField(max_length=5, null=True, blank=True, editable=False) class Meta: db_table = 'users' def __init__(self, *args, **kw): super(UserProfile, self).__init__(*args, **kw) if self.username: self.username = smart_unicode(self.username) def __unicode__(self): return u'%s: %s' % (self.id, self.display_name or self.username) def save(self, force_insert=False, force_update=False, using=None, **kwargs): # we have to fix stupid things that we defined poorly in remora if not self.resetcode_expires: self.resetcode_expires = datetime.now() super(UserProfile, self).save(force_insert, force_update, using, **kwargs) @property def is_superuser(self): return self.groups.filter(rules='*:*').exists() @property def is_staff(self): from mkt.access import acl return acl.action_allowed_user(self, 'Admin', '%') def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser def get_backend(self): return 'django_browserid.auth.BrowserIDBackend' def set_backend(self, val): pass backend = property(get_backend, set_backend) def is_anonymous(self): return False def get_url_path(self, src=None): # See: bug 880767. return '#' def my_apps(self, n=8): """Returns n apps""" qs = self.addons.filter(type=amo.ADDON_WEBAPP) qs = order_by_translation(qs, 'name') return qs[:n] @amo.cached_property def is_developer(self): return self.addonuser_set.exists() @property def name(self): return smart_unicode(self.display_name or self.username) @amo.cached_property def reviews(self): """All reviews that are not dev replies.""" qs = self._reviews_all.filter(reply_to=None) # Force the query to occur immediately. Several # reviews-related tests hang if this isn't done. return qs def anonymize(self): log.info(u"User (%s: <%s>) is being anonymized." % (self, self.email)) self.email = None self.password = "sha512$Anonymous$Password" self.username = "Anonymous-%s" % self.id # Can't be null self.display_name = None self.homepage = "" self.deleted = True self.picture_type = "" self.save() def check_password(self, raw_password): # BrowserID does not store a password. return True def log_login_attempt(self, successful): """Log a user's login attempt""" self.last_login_attempt = datetime.now() self.last_login_attempt_ip = commonware.log.get_remote_addr() if successful: log.debug(u"User (%s) logged in successfully" % self) self.failed_login_attempts = 0 self.last_login_ip = commonware.log.get_remote_addr() else: log.debug(u"User (%s) failed to log in" % self) if self.failed_login_attempts < 16777216: self.failed_login_attempts += 1 self.save() def purchase_ids(self): """ I'm special casing this because we use purchase_ids a lot in the site and we are not caching empty querysets in cache-machine. That means that when the site is first launched we are having a lot of empty queries hit. We can probably do this in smarter fashion by making cache-machine cache empty queries on an as need basis. """ # Circular import from mkt.prices.models import AddonPurchase @memoize(prefix='users:purchase-ids') def ids(pk): return (AddonPurchase.objects.filter(user=pk) .values_list('addon_id', flat=True) .filter(type=amo.CONTRIB_PURCHASE) .order_by('pk')) return ids(self.pk) @contextmanager def activate_lang(self): """ Activate the language for the user. If none is set will go to the site default which is en-US. """ lang = self.lang if self.lang else settings.LANGUAGE_CODE old = translation.get_language() tower.activate(lang) yield tower.activate(old) models.signals.pre_save.connect(save_signal, sender=UserProfile, dispatch_uid='userprofile_translations') class
(amo.models.ModelBase): user = models.ForeignKey(UserProfile, related_name='notifications') notification_id = models.IntegerField() enabled = models.BooleanField(default=False) class Meta: db_table = 'users_notifications' @staticmethod def update_or_create(update={}, **kwargs): rows = UserNotification.objects.filter(**kwargs).update(**update) if not rows: update.update(dict(**kwargs)) UserNotification.objects.create(**update)
UserNotification
identifier_name
models.py
from contextlib import contextmanager from datetime import datetime from django import forms from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core import validators from django.db import models from django.utils import translation from django.utils.encoding import smart_unicode from django.utils.functional import lazy import commonware.log import tower from cache_nuggets.lib import memoize from tower import ugettext as _ import amo import amo.models from amo.urlresolvers import reverse from mkt.translations.fields import NoLinksField, save_signal from mkt.translations.query import order_by_translation log = commonware.log.getLogger('z.users') class UserForeignKey(models.ForeignKey): """ A replacement for models.ForeignKey('users.UserProfile'). This field uses UserEmailField to make form fields key off the user's email instead of the primary key id. We also hook up autocomplete automatically. """ def __init__(self, *args, **kw): super(UserForeignKey, self).__init__(UserProfile, *args, **kw) def value_from_object(self, obj): return getattr(obj, self.name).email def formfield(self, **kw): defaults = {'form_class': UserEmailField} defaults.update(kw) return models.Field.formfield(self, **defaults) class UserEmailField(forms.EmailField): def clean(self, value): if value in validators.EMPTY_VALUES: raise forms.ValidationError(self.error_messages['required']) try: return UserProfile.objects.get(email=value) except UserProfile.DoesNotExist: raise forms.ValidationError(_('No user with that email.')) def widget_attrs(self, widget): lazy_reverse = lazy(reverse, str) return {'class': 'email-autocomplete', 'data-src': lazy_reverse('users.ajax')} AbstractBaseUser._meta.get_field('password').max_length = 255 class UserProfile(amo.models.OnChangeMixin, amo.models.ModelBase, AbstractBaseUser): USERNAME_FIELD = 'username' username = models.CharField(max_length=255, default='', unique=True) display_name = models.CharField(max_length=255, default='', null=True, blank=True) email = models.EmailField(unique=True, null=True) averagerating = models.CharField(max_length=255, blank=True, null=True) bio = NoLinksField(short=False) confirmationcode = models.CharField(max_length=255, default='', blank=True) deleted = models.BooleanField(default=False) display_collections = models.BooleanField(default=False) display_collections_fav = models.BooleanField(default=False) emailhidden = models.BooleanField(default=True) homepage = models.URLField(max_length=255, blank=True, default='') location = models.CharField(max_length=255, blank=True, default='') notes = models.TextField(blank=True, null=True) notifycompat = models.BooleanField(default=True) notifyevents = models.BooleanField(default=True) occupation = models.CharField(max_length=255, default='', blank=True) # This is essentially a "has_picture" flag right now picture_type = models.CharField(max_length=75, default='', blank=True) resetcode = models.CharField(max_length=255, default='', blank=True) resetcode_expires = models.DateTimeField(default=datetime.now, null=True, blank=True) read_dev_agreement = models.DateTimeField(null=True, blank=True) last_login_ip = models.CharField(default='', max_length=45, editable=False) last_login_attempt = models.DateTimeField(null=True, editable=False) last_login_attempt_ip = models.CharField(default='', max_length=45, editable=False) failed_login_attempts = models.PositiveIntegerField(default=0, editable=False) source = models.PositiveIntegerField(default=amo.LOGIN_SOURCE_UNKNOWN, editable=False, db_index=True) is_verified = models.BooleanField(default=True) region = models.CharField(max_length=11, null=True, blank=True, editable=False) lang = models.CharField(max_length=5, null=True, blank=True, editable=False) class Meta: db_table = 'users' def __init__(self, *args, **kw): super(UserProfile, self).__init__(*args, **kw) if self.username: self.username = smart_unicode(self.username) def __unicode__(self): return u'%s: %s' % (self.id, self.display_name or self.username) def save(self, force_insert=False, force_update=False, using=None, **kwargs): # we have to fix stupid things that we defined poorly in remora if not self.resetcode_expires: self.resetcode_expires = datetime.now() super(UserProfile, self).save(force_insert, force_update, using, **kwargs) @property def is_superuser(self): return self.groups.filter(rules='*:*').exists() @property def is_staff(self): from mkt.access import acl return acl.action_allowed_user(self, 'Admin', '%') def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser def get_backend(self): return 'django_browserid.auth.BrowserIDBackend' def set_backend(self, val): pass backend = property(get_backend, set_backend) def is_anonymous(self):
def get_url_path(self, src=None): # See: bug 880767. return '#' def my_apps(self, n=8): """Returns n apps""" qs = self.addons.filter(type=amo.ADDON_WEBAPP) qs = order_by_translation(qs, 'name') return qs[:n] @amo.cached_property def is_developer(self): return self.addonuser_set.exists() @property def name(self): return smart_unicode(self.display_name or self.username) @amo.cached_property def reviews(self): """All reviews that are not dev replies.""" qs = self._reviews_all.filter(reply_to=None) # Force the query to occur immediately. Several # reviews-related tests hang if this isn't done. return qs def anonymize(self): log.info(u"User (%s: <%s>) is being anonymized." % (self, self.email)) self.email = None self.password = "sha512$Anonymous$Password" self.username = "Anonymous-%s" % self.id # Can't be null self.display_name = None self.homepage = "" self.deleted = True self.picture_type = "" self.save() def check_password(self, raw_password): # BrowserID does not store a password. return True def log_login_attempt(self, successful): """Log a user's login attempt""" self.last_login_attempt = datetime.now() self.last_login_attempt_ip = commonware.log.get_remote_addr() if successful: log.debug(u"User (%s) logged in successfully" % self) self.failed_login_attempts = 0 self.last_login_ip = commonware.log.get_remote_addr() else: log.debug(u"User (%s) failed to log in" % self) if self.failed_login_attempts < 16777216: self.failed_login_attempts += 1 self.save() def purchase_ids(self): """ I'm special casing this because we use purchase_ids a lot in the site and we are not caching empty querysets in cache-machine. That means that when the site is first launched we are having a lot of empty queries hit. We can probably do this in smarter fashion by making cache-machine cache empty queries on an as need basis. """ # Circular import from mkt.prices.models import AddonPurchase @memoize(prefix='users:purchase-ids') def ids(pk): return (AddonPurchase.objects.filter(user=pk) .values_list('addon_id', flat=True) .filter(type=amo.CONTRIB_PURCHASE) .order_by('pk')) return ids(self.pk) @contextmanager def activate_lang(self): """ Activate the language for the user. If none is set will go to the site default which is en-US. """ lang = self.lang if self.lang else settings.LANGUAGE_CODE old = translation.get_language() tower.activate(lang) yield tower.activate(old) models.signals.pre_save.connect(save_signal, sender=UserProfile, dispatch_uid='userprofile_translations') class UserNotification(amo.models.ModelBase): user = models.ForeignKey(UserProfile, related_name='notifications') notification_id = models.IntegerField() enabled = models.BooleanField(default=False) class Meta: db_table = 'users_notifications' @staticmethod def update_or_create(update={}, **kwargs): rows = UserNotification.objects.filter(**kwargs).update(**update) if not rows: update.update(dict(**kwargs)) UserNotification.objects.create(**update)
return False
identifier_body
models.py
from contextlib import contextmanager from datetime import datetime from django import forms from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core import validators from django.db import models from django.utils import translation from django.utils.encoding import smart_unicode from django.utils.functional import lazy import commonware.log import tower from cache_nuggets.lib import memoize from tower import ugettext as _ import amo import amo.models from amo.urlresolvers import reverse from mkt.translations.fields import NoLinksField, save_signal from mkt.translations.query import order_by_translation log = commonware.log.getLogger('z.users') class UserForeignKey(models.ForeignKey): """ A replacement for models.ForeignKey('users.UserProfile'). This field uses UserEmailField to make form fields key off the user's email instead of the primary key id. We also hook up autocomplete automatically. """ def __init__(self, *args, **kw): super(UserForeignKey, self).__init__(UserProfile, *args, **kw) def value_from_object(self, obj): return getattr(obj, self.name).email def formfield(self, **kw): defaults = {'form_class': UserEmailField} defaults.update(kw) return models.Field.formfield(self, **defaults) class UserEmailField(forms.EmailField): def clean(self, value): if value in validators.EMPTY_VALUES: raise forms.ValidationError(self.error_messages['required']) try: return UserProfile.objects.get(email=value) except UserProfile.DoesNotExist: raise forms.ValidationError(_('No user with that email.')) def widget_attrs(self, widget): lazy_reverse = lazy(reverse, str) return {'class': 'email-autocomplete', 'data-src': lazy_reverse('users.ajax')} AbstractBaseUser._meta.get_field('password').max_length = 255 class UserProfile(amo.models.OnChangeMixin, amo.models.ModelBase, AbstractBaseUser): USERNAME_FIELD = 'username' username = models.CharField(max_length=255, default='', unique=True) display_name = models.CharField(max_length=255, default='', null=True, blank=True) email = models.EmailField(unique=True, null=True) averagerating = models.CharField(max_length=255, blank=True, null=True) bio = NoLinksField(short=False) confirmationcode = models.CharField(max_length=255, default='', blank=True) deleted = models.BooleanField(default=False) display_collections = models.BooleanField(default=False) display_collections_fav = models.BooleanField(default=False) emailhidden = models.BooleanField(default=True) homepage = models.URLField(max_length=255, blank=True, default='') location = models.CharField(max_length=255, blank=True, default='') notes = models.TextField(blank=True, null=True) notifycompat = models.BooleanField(default=True) notifyevents = models.BooleanField(default=True) occupation = models.CharField(max_length=255, default='', blank=True) # This is essentially a "has_picture" flag right now picture_type = models.CharField(max_length=75, default='', blank=True) resetcode = models.CharField(max_length=255, default='', blank=True) resetcode_expires = models.DateTimeField(default=datetime.now, null=True, blank=True) read_dev_agreement = models.DateTimeField(null=True, blank=True) last_login_ip = models.CharField(default='', max_length=45, editable=False) last_login_attempt = models.DateTimeField(null=True, editable=False) last_login_attempt_ip = models.CharField(default='', max_length=45, editable=False) failed_login_attempts = models.PositiveIntegerField(default=0, editable=False) source = models.PositiveIntegerField(default=amo.LOGIN_SOURCE_UNKNOWN, editable=False, db_index=True) is_verified = models.BooleanField(default=True) region = models.CharField(max_length=11, null=True, blank=True, editable=False) lang = models.CharField(max_length=5, null=True, blank=True, editable=False) class Meta: db_table = 'users' def __init__(self, *args, **kw): super(UserProfile, self).__init__(*args, **kw) if self.username: self.username = smart_unicode(self.username) def __unicode__(self): return u'%s: %s' % (self.id, self.display_name or self.username) def save(self, force_insert=False, force_update=False, using=None, **kwargs): # we have to fix stupid things that we defined poorly in remora if not self.resetcode_expires: self.resetcode_expires = datetime.now() super(UserProfile, self).save(force_insert, force_update, using, **kwargs) @property def is_superuser(self): return self.groups.filter(rules='*:*').exists() @property def is_staff(self): from mkt.access import acl return acl.action_allowed_user(self, 'Admin', '%') def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser def get_backend(self): return 'django_browserid.auth.BrowserIDBackend' def set_backend(self, val): pass backend = property(get_backend, set_backend) def is_anonymous(self): return False def get_url_path(self, src=None): # See: bug 880767. return '#' def my_apps(self, n=8): """Returns n apps""" qs = self.addons.filter(type=amo.ADDON_WEBAPP) qs = order_by_translation(qs, 'name') return qs[:n] @amo.cached_property def is_developer(self): return self.addonuser_set.exists() @property def name(self): return smart_unicode(self.display_name or self.username) @amo.cached_property def reviews(self): """All reviews that are not dev replies.""" qs = self._reviews_all.filter(reply_to=None) # Force the query to occur immediately. Several # reviews-related tests hang if this isn't done. return qs def anonymize(self): log.info(u"User (%s: <%s>) is being anonymized." % (self, self.email)) self.email = None self.password = "sha512$Anonymous$Password" self.username = "Anonymous-%s" % self.id # Can't be null self.display_name = None self.homepage = "" self.deleted = True self.picture_type = "" self.save() def check_password(self, raw_password): # BrowserID does not store a password. return True def log_login_attempt(self, successful): """Log a user's login attempt""" self.last_login_attempt = datetime.now() self.last_login_attempt_ip = commonware.log.get_remote_addr() if successful: log.debug(u"User (%s) logged in successfully" % self) self.failed_login_attempts = 0 self.last_login_ip = commonware.log.get_remote_addr() else:
self.save() def purchase_ids(self): """ I'm special casing this because we use purchase_ids a lot in the site and we are not caching empty querysets in cache-machine. That means that when the site is first launched we are having a lot of empty queries hit. We can probably do this in smarter fashion by making cache-machine cache empty queries on an as need basis. """ # Circular import from mkt.prices.models import AddonPurchase @memoize(prefix='users:purchase-ids') def ids(pk): return (AddonPurchase.objects.filter(user=pk) .values_list('addon_id', flat=True) .filter(type=amo.CONTRIB_PURCHASE) .order_by('pk')) return ids(self.pk) @contextmanager def activate_lang(self): """ Activate the language for the user. If none is set will go to the site default which is en-US. """ lang = self.lang if self.lang else settings.LANGUAGE_CODE old = translation.get_language() tower.activate(lang) yield tower.activate(old) models.signals.pre_save.connect(save_signal, sender=UserProfile, dispatch_uid='userprofile_translations') class UserNotification(amo.models.ModelBase): user = models.ForeignKey(UserProfile, related_name='notifications') notification_id = models.IntegerField() enabled = models.BooleanField(default=False) class Meta: db_table = 'users_notifications' @staticmethod def update_or_create(update={}, **kwargs): rows = UserNotification.objects.filter(**kwargs).update(**update) if not rows: update.update(dict(**kwargs)) UserNotification.objects.create(**update)
log.debug(u"User (%s) failed to log in" % self) if self.failed_login_attempts < 16777216: self.failed_login_attempts += 1
conditional_block
models.py
from contextlib import contextmanager from datetime import datetime from django import forms from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core import validators from django.db import models from django.utils import translation from django.utils.encoding import smart_unicode from django.utils.functional import lazy import commonware.log import tower from cache_nuggets.lib import memoize from tower import ugettext as _ import amo import amo.models from amo.urlresolvers import reverse from mkt.translations.fields import NoLinksField, save_signal
class UserForeignKey(models.ForeignKey): """ A replacement for models.ForeignKey('users.UserProfile'). This field uses UserEmailField to make form fields key off the user's email instead of the primary key id. We also hook up autocomplete automatically. """ def __init__(self, *args, **kw): super(UserForeignKey, self).__init__(UserProfile, *args, **kw) def value_from_object(self, obj): return getattr(obj, self.name).email def formfield(self, **kw): defaults = {'form_class': UserEmailField} defaults.update(kw) return models.Field.formfield(self, **defaults) class UserEmailField(forms.EmailField): def clean(self, value): if value in validators.EMPTY_VALUES: raise forms.ValidationError(self.error_messages['required']) try: return UserProfile.objects.get(email=value) except UserProfile.DoesNotExist: raise forms.ValidationError(_('No user with that email.')) def widget_attrs(self, widget): lazy_reverse = lazy(reverse, str) return {'class': 'email-autocomplete', 'data-src': lazy_reverse('users.ajax')} AbstractBaseUser._meta.get_field('password').max_length = 255 class UserProfile(amo.models.OnChangeMixin, amo.models.ModelBase, AbstractBaseUser): USERNAME_FIELD = 'username' username = models.CharField(max_length=255, default='', unique=True) display_name = models.CharField(max_length=255, default='', null=True, blank=True) email = models.EmailField(unique=True, null=True) averagerating = models.CharField(max_length=255, blank=True, null=True) bio = NoLinksField(short=False) confirmationcode = models.CharField(max_length=255, default='', blank=True) deleted = models.BooleanField(default=False) display_collections = models.BooleanField(default=False) display_collections_fav = models.BooleanField(default=False) emailhidden = models.BooleanField(default=True) homepage = models.URLField(max_length=255, blank=True, default='') location = models.CharField(max_length=255, blank=True, default='') notes = models.TextField(blank=True, null=True) notifycompat = models.BooleanField(default=True) notifyevents = models.BooleanField(default=True) occupation = models.CharField(max_length=255, default='', blank=True) # This is essentially a "has_picture" flag right now picture_type = models.CharField(max_length=75, default='', blank=True) resetcode = models.CharField(max_length=255, default='', blank=True) resetcode_expires = models.DateTimeField(default=datetime.now, null=True, blank=True) read_dev_agreement = models.DateTimeField(null=True, blank=True) last_login_ip = models.CharField(default='', max_length=45, editable=False) last_login_attempt = models.DateTimeField(null=True, editable=False) last_login_attempt_ip = models.CharField(default='', max_length=45, editable=False) failed_login_attempts = models.PositiveIntegerField(default=0, editable=False) source = models.PositiveIntegerField(default=amo.LOGIN_SOURCE_UNKNOWN, editable=False, db_index=True) is_verified = models.BooleanField(default=True) region = models.CharField(max_length=11, null=True, blank=True, editable=False) lang = models.CharField(max_length=5, null=True, blank=True, editable=False) class Meta: db_table = 'users' def __init__(self, *args, **kw): super(UserProfile, self).__init__(*args, **kw) if self.username: self.username = smart_unicode(self.username) def __unicode__(self): return u'%s: %s' % (self.id, self.display_name or self.username) def save(self, force_insert=False, force_update=False, using=None, **kwargs): # we have to fix stupid things that we defined poorly in remora if not self.resetcode_expires: self.resetcode_expires = datetime.now() super(UserProfile, self).save(force_insert, force_update, using, **kwargs) @property def is_superuser(self): return self.groups.filter(rules='*:*').exists() @property def is_staff(self): from mkt.access import acl return acl.action_allowed_user(self, 'Admin', '%') def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser def get_backend(self): return 'django_browserid.auth.BrowserIDBackend' def set_backend(self, val): pass backend = property(get_backend, set_backend) def is_anonymous(self): return False def get_url_path(self, src=None): # See: bug 880767. return '#' def my_apps(self, n=8): """Returns n apps""" qs = self.addons.filter(type=amo.ADDON_WEBAPP) qs = order_by_translation(qs, 'name') return qs[:n] @amo.cached_property def is_developer(self): return self.addonuser_set.exists() @property def name(self): return smart_unicode(self.display_name or self.username) @amo.cached_property def reviews(self): """All reviews that are not dev replies.""" qs = self._reviews_all.filter(reply_to=None) # Force the query to occur immediately. Several # reviews-related tests hang if this isn't done. return qs def anonymize(self): log.info(u"User (%s: <%s>) is being anonymized." % (self, self.email)) self.email = None self.password = "sha512$Anonymous$Password" self.username = "Anonymous-%s" % self.id # Can't be null self.display_name = None self.homepage = "" self.deleted = True self.picture_type = "" self.save() def check_password(self, raw_password): # BrowserID does not store a password. return True def log_login_attempt(self, successful): """Log a user's login attempt""" self.last_login_attempt = datetime.now() self.last_login_attempt_ip = commonware.log.get_remote_addr() if successful: log.debug(u"User (%s) logged in successfully" % self) self.failed_login_attempts = 0 self.last_login_ip = commonware.log.get_remote_addr() else: log.debug(u"User (%s) failed to log in" % self) if self.failed_login_attempts < 16777216: self.failed_login_attempts += 1 self.save() def purchase_ids(self): """ I'm special casing this because we use purchase_ids a lot in the site and we are not caching empty querysets in cache-machine. That means that when the site is first launched we are having a lot of empty queries hit. We can probably do this in smarter fashion by making cache-machine cache empty queries on an as need basis. """ # Circular import from mkt.prices.models import AddonPurchase @memoize(prefix='users:purchase-ids') def ids(pk): return (AddonPurchase.objects.filter(user=pk) .values_list('addon_id', flat=True) .filter(type=amo.CONTRIB_PURCHASE) .order_by('pk')) return ids(self.pk) @contextmanager def activate_lang(self): """ Activate the language for the user. If none is set will go to the site default which is en-US. """ lang = self.lang if self.lang else settings.LANGUAGE_CODE old = translation.get_language() tower.activate(lang) yield tower.activate(old) models.signals.pre_save.connect(save_signal, sender=UserProfile, dispatch_uid='userprofile_translations') class UserNotification(amo.models.ModelBase): user = models.ForeignKey(UserProfile, related_name='notifications') notification_id = models.IntegerField() enabled = models.BooleanField(default=False) class Meta: db_table = 'users_notifications' @staticmethod def update_or_create(update={}, **kwargs): rows = UserNotification.objects.filter(**kwargs).update(**update) if not rows: update.update(dict(**kwargs)) UserNotification.objects.create(**update)
from mkt.translations.query import order_by_translation log = commonware.log.getLogger('z.users')
random_line_split
create_bidder_level_filter_set.py
#!/usr/bin/python # # Copyright 2017 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. """This example creates a bidder-level filter set. A bidder-level filter set can be used to retrieve aggregated data for all Authorized Buyers accounts under the given bidder account, including the bidder account itself. """ import argparse from datetime import date from datetime import datetime from datetime import timedelta import os import pprint import sys import uuid sys.path.insert(0, os.path.abspath('..')) from googleapiclient.errors import HttpError import samples_util _DATE_FORMAT = '%Y%m%d' _FILTER_SET_NAME_TEMPLATE = ('bidders/{bidders_resource_id}/' 'filterSets/{filtersets_resource_id}') _OWNER_NAME_TEMPLATE = 'bidders/{bidders_resource_id}' _TODAY = date.today() _VALID_ENVIRONMENTS = ('WEB', 'APP') _VALID_FORMATS = ('DISPLAY', 'VIDEO') _VALID_PLATFORMS = ('DESKTOP', 'TABLET', 'MOBILE') _VALID_TIME_SERIES_GRANULARITIES = ('HOURLY', 'DAILY') DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE' DEFAULT_FILTER_SET_RESOURCE_ID = f'FilterSet_{uuid.uuid4()}' DEFAULT_END_DATE = _TODAY.strftime(_DATE_FORMAT) DEFAULT_START_DATE = (_TODAY - timedelta(days=7)).strftime( _DATE_FORMAT) def main(ad_exchange_buyer, owner_name, body, is_transient): try: # Construct and execute the request. filter_set = ad_exchange_buyer.bidders().filterSets().create( ownerName=owner_name, isTransient=is_transient, body=body).execute() print(f'FilterSet created for bidder: "{owner_name}".') pprint.pprint(filter_set) except HttpError as e: print(e) if __name__ == '__main__': def time_series_granularity_type(s): if s not in _VALID_TIME_SERIES_GRANULARITIES:
def environment_type(s): if s not in _VALID_ENVIRONMENTS: raise argparse.ArgumentTypeError( f'Invalid Environment specified: "{s}".') return s def format_type(s): if s not in _VALID_FORMATS: raise argparse.ArgumentTypeError(f'Invalid Format specified: "{s}".') return s def platform_type(s): if s not in _VALID_PLATFORMS: raise argparse.ArgumentTypeError(f'Invalid Platform specified: "{s}".') return s def valid_date(s): try: return datetime.strptime(s, _DATE_FORMAT).date() except ValueError: raise argparse.ArgumentTypeError(f'Invalid date specified: "{s}".') parser = argparse.ArgumentParser( description=('Creates a bidder-level filter set with the specified ' 'options.')) # Required fields. parser.add_argument( '-b', '--bidder_resource_id', default=DEFAULT_BIDDER_RESOURCE_ID, help=('The resource ID of the bidders resource for which the filter set ' 'is being created. This will be used to construct the ownerName ' 'used as a path parameter for filter set requests. For additional ' 'information on how to configure the ownerName path parameter, ' 'see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets/create' '#body.PATH_PARAMETERS.owner_name')) parser.add_argument( '-r', '--resource_id', default=DEFAULT_FILTER_SET_RESOURCE_ID, help=('The resource ID of the filter set. Note that this must be ' 'unique. This will be used to construct the filter set\'s name. ' 'For additional information on how to configure a filter set\'s ' 'name, see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets#FilterSet.FIELDS.name')) parser.add_argument( '--end_date', default=DEFAULT_END_DATE, type=valid_date, help=('The end date for the filter set\'s absoluteDateRange field, which ' 'will be accepted in this example in YYYYMMDD format.')) parser.add_argument( '--start_date', default=DEFAULT_START_DATE, type=valid_date, help=('The start date for the filter set\'s time_range field, which ' 'will be accepted in this example in YYYYMMDD format.')) # Optional fields. parser.add_argument( '-e', '--environment', required=False, type=environment_type, help=('The environment on which to filter.')) parser.add_argument( '-f', '--format', required=False, type=format_type, help=('The format on which to filter.')) parser.add_argument( '-p', '--platforms', required=False, nargs='*', type=platform_type, help=('The platforms on which to filter. The filters represented by ' 'multiple platforms are ORed together. Note that you may specify ' 'more than one using a space as a delimiter.')) parser.add_argument( '-s', '--seller_network_ids', required=False, nargs='*', type=int, help=('The list of IDs for seller networks on which to filter. The ' 'filters represented by multiple seller network IDs are ORed ' 'together. Note that you may specify more than one using a space ' 'as a delimiter.')) parser.add_argument( '-t', '--time_series_granularity', required=False, type=time_series_granularity_type, help=('The granularity of time intervals if a time series breakdown is ' 'desired.')) parser.add_argument( '--is_transient', required=False, default=True, type=bool, help=('Whether the filter set is transient, or should be persisted ' 'indefinitely. In this example, this will default to True.')) args = parser.parse_args() # Build the time_range as an AbsoluteDateRange. time_range = { 'startDate': { 'year': args.start_date.year, 'month': args.start_date.month, 'day': args.start_date.day }, 'endDate': { 'year': args.end_date.year, 'month': args.end_date.month, 'day': args.end_date.day } } # Create a body containing the required fields. BODY = { 'name': _FILTER_SET_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id, filtersets_resource_id=args.resource_id), # Note: You may alternatively specify relativeDateRange or # realtimeTimeRange. 'absoluteDateRange': time_range } # Add optional fields to body if specified. if args.environment: BODY['environment'] = args.environment if args.format: BODY['format'] = args.format if args.platforms: BODY['platforms'] = args.platforms if args.seller_network_ids: BODY['sellerNetworkIds'] = args.seller_network_ids if args.time_series_granularity: BODY['timeSeriesGranularity'] = args.time_series_granularity try: service = samples_util.GetService('v2beta1') except IOError as ex: print(f'Unable to create adexchangebuyer service - {ex}') print('Did you specify the key file in samples_util.py?') sys.exit(1) main(service, _OWNER_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id), BODY, args.is_transient)
raise argparse.ArgumentTypeError('Invalid TimeSeriesGranularity ' f'specified: "{s}".') return s
random_line_split
create_bidder_level_filter_set.py
#!/usr/bin/python # # Copyright 2017 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. """This example creates a bidder-level filter set. A bidder-level filter set can be used to retrieve aggregated data for all Authorized Buyers accounts under the given bidder account, including the bidder account itself. """ import argparse from datetime import date from datetime import datetime from datetime import timedelta import os import pprint import sys import uuid sys.path.insert(0, os.path.abspath('..')) from googleapiclient.errors import HttpError import samples_util _DATE_FORMAT = '%Y%m%d' _FILTER_SET_NAME_TEMPLATE = ('bidders/{bidders_resource_id}/' 'filterSets/{filtersets_resource_id}') _OWNER_NAME_TEMPLATE = 'bidders/{bidders_resource_id}' _TODAY = date.today() _VALID_ENVIRONMENTS = ('WEB', 'APP') _VALID_FORMATS = ('DISPLAY', 'VIDEO') _VALID_PLATFORMS = ('DESKTOP', 'TABLET', 'MOBILE') _VALID_TIME_SERIES_GRANULARITIES = ('HOURLY', 'DAILY') DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE' DEFAULT_FILTER_SET_RESOURCE_ID = f'FilterSet_{uuid.uuid4()}' DEFAULT_END_DATE = _TODAY.strftime(_DATE_FORMAT) DEFAULT_START_DATE = (_TODAY - timedelta(days=7)).strftime( _DATE_FORMAT) def main(ad_exchange_buyer, owner_name, body, is_transient): try: # Construct and execute the request. filter_set = ad_exchange_buyer.bidders().filterSets().create( ownerName=owner_name, isTransient=is_transient, body=body).execute() print(f'FilterSet created for bidder: "{owner_name}".') pprint.pprint(filter_set) except HttpError as e: print(e) if __name__ == '__main__': def time_series_granularity_type(s): if s not in _VALID_TIME_SERIES_GRANULARITIES: raise argparse.ArgumentTypeError('Invalid TimeSeriesGranularity ' f'specified: "{s}".') return s def environment_type(s): if s not in _VALID_ENVIRONMENTS: raise argparse.ArgumentTypeError( f'Invalid Environment specified: "{s}".') return s def format_type(s): if s not in _VALID_FORMATS: raise argparse.ArgumentTypeError(f'Invalid Format specified: "{s}".') return s def
(s): if s not in _VALID_PLATFORMS: raise argparse.ArgumentTypeError(f'Invalid Platform specified: "{s}".') return s def valid_date(s): try: return datetime.strptime(s, _DATE_FORMAT).date() except ValueError: raise argparse.ArgumentTypeError(f'Invalid date specified: "{s}".') parser = argparse.ArgumentParser( description=('Creates a bidder-level filter set with the specified ' 'options.')) # Required fields. parser.add_argument( '-b', '--bidder_resource_id', default=DEFAULT_BIDDER_RESOURCE_ID, help=('The resource ID of the bidders resource for which the filter set ' 'is being created. This will be used to construct the ownerName ' 'used as a path parameter for filter set requests. For additional ' 'information on how to configure the ownerName path parameter, ' 'see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets/create' '#body.PATH_PARAMETERS.owner_name')) parser.add_argument( '-r', '--resource_id', default=DEFAULT_FILTER_SET_RESOURCE_ID, help=('The resource ID of the filter set. Note that this must be ' 'unique. This will be used to construct the filter set\'s name. ' 'For additional information on how to configure a filter set\'s ' 'name, see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets#FilterSet.FIELDS.name')) parser.add_argument( '--end_date', default=DEFAULT_END_DATE, type=valid_date, help=('The end date for the filter set\'s absoluteDateRange field, which ' 'will be accepted in this example in YYYYMMDD format.')) parser.add_argument( '--start_date', default=DEFAULT_START_DATE, type=valid_date, help=('The start date for the filter set\'s time_range field, which ' 'will be accepted in this example in YYYYMMDD format.')) # Optional fields. parser.add_argument( '-e', '--environment', required=False, type=environment_type, help=('The environment on which to filter.')) parser.add_argument( '-f', '--format', required=False, type=format_type, help=('The format on which to filter.')) parser.add_argument( '-p', '--platforms', required=False, nargs='*', type=platform_type, help=('The platforms on which to filter. The filters represented by ' 'multiple platforms are ORed together. Note that you may specify ' 'more than one using a space as a delimiter.')) parser.add_argument( '-s', '--seller_network_ids', required=False, nargs='*', type=int, help=('The list of IDs for seller networks on which to filter. The ' 'filters represented by multiple seller network IDs are ORed ' 'together. Note that you may specify more than one using a space ' 'as a delimiter.')) parser.add_argument( '-t', '--time_series_granularity', required=False, type=time_series_granularity_type, help=('The granularity of time intervals if a time series breakdown is ' 'desired.')) parser.add_argument( '--is_transient', required=False, default=True, type=bool, help=('Whether the filter set is transient, or should be persisted ' 'indefinitely. In this example, this will default to True.')) args = parser.parse_args() # Build the time_range as an AbsoluteDateRange. time_range = { 'startDate': { 'year': args.start_date.year, 'month': args.start_date.month, 'day': args.start_date.day }, 'endDate': { 'year': args.end_date.year, 'month': args.end_date.month, 'day': args.end_date.day } } # Create a body containing the required fields. BODY = { 'name': _FILTER_SET_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id, filtersets_resource_id=args.resource_id), # Note: You may alternatively specify relativeDateRange or # realtimeTimeRange. 'absoluteDateRange': time_range } # Add optional fields to body if specified. if args.environment: BODY['environment'] = args.environment if args.format: BODY['format'] = args.format if args.platforms: BODY['platforms'] = args.platforms if args.seller_network_ids: BODY['sellerNetworkIds'] = args.seller_network_ids if args.time_series_granularity: BODY['timeSeriesGranularity'] = args.time_series_granularity try: service = samples_util.GetService('v2beta1') except IOError as ex: print(f'Unable to create adexchangebuyer service - {ex}') print('Did you specify the key file in samples_util.py?') sys.exit(1) main(service, _OWNER_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id), BODY, args.is_transient)
platform_type
identifier_name
create_bidder_level_filter_set.py
#!/usr/bin/python # # Copyright 2017 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. """This example creates a bidder-level filter set. A bidder-level filter set can be used to retrieve aggregated data for all Authorized Buyers accounts under the given bidder account, including the bidder account itself. """ import argparse from datetime import date from datetime import datetime from datetime import timedelta import os import pprint import sys import uuid sys.path.insert(0, os.path.abspath('..')) from googleapiclient.errors import HttpError import samples_util _DATE_FORMAT = '%Y%m%d' _FILTER_SET_NAME_TEMPLATE = ('bidders/{bidders_resource_id}/' 'filterSets/{filtersets_resource_id}') _OWNER_NAME_TEMPLATE = 'bidders/{bidders_resource_id}' _TODAY = date.today() _VALID_ENVIRONMENTS = ('WEB', 'APP') _VALID_FORMATS = ('DISPLAY', 'VIDEO') _VALID_PLATFORMS = ('DESKTOP', 'TABLET', 'MOBILE') _VALID_TIME_SERIES_GRANULARITIES = ('HOURLY', 'DAILY') DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE' DEFAULT_FILTER_SET_RESOURCE_ID = f'FilterSet_{uuid.uuid4()}' DEFAULT_END_DATE = _TODAY.strftime(_DATE_FORMAT) DEFAULT_START_DATE = (_TODAY - timedelta(days=7)).strftime( _DATE_FORMAT) def main(ad_exchange_buyer, owner_name, body, is_transient): try: # Construct and execute the request. filter_set = ad_exchange_buyer.bidders().filterSets().create( ownerName=owner_name, isTransient=is_transient, body=body).execute() print(f'FilterSet created for bidder: "{owner_name}".') pprint.pprint(filter_set) except HttpError as e: print(e) if __name__ == '__main__': def time_series_granularity_type(s):
def environment_type(s): if s not in _VALID_ENVIRONMENTS: raise argparse.ArgumentTypeError( f'Invalid Environment specified: "{s}".') return s def format_type(s): if s not in _VALID_FORMATS: raise argparse.ArgumentTypeError(f'Invalid Format specified: "{s}".') return s def platform_type(s): if s not in _VALID_PLATFORMS: raise argparse.ArgumentTypeError(f'Invalid Platform specified: "{s}".') return s def valid_date(s): try: return datetime.strptime(s, _DATE_FORMAT).date() except ValueError: raise argparse.ArgumentTypeError(f'Invalid date specified: "{s}".') parser = argparse.ArgumentParser( description=('Creates a bidder-level filter set with the specified ' 'options.')) # Required fields. parser.add_argument( '-b', '--bidder_resource_id', default=DEFAULT_BIDDER_RESOURCE_ID, help=('The resource ID of the bidders resource for which the filter set ' 'is being created. This will be used to construct the ownerName ' 'used as a path parameter for filter set requests. For additional ' 'information on how to configure the ownerName path parameter, ' 'see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets/create' '#body.PATH_PARAMETERS.owner_name')) parser.add_argument( '-r', '--resource_id', default=DEFAULT_FILTER_SET_RESOURCE_ID, help=('The resource ID of the filter set. Note that this must be ' 'unique. This will be used to construct the filter set\'s name. ' 'For additional information on how to configure a filter set\'s ' 'name, see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets#FilterSet.FIELDS.name')) parser.add_argument( '--end_date', default=DEFAULT_END_DATE, type=valid_date, help=('The end date for the filter set\'s absoluteDateRange field, which ' 'will be accepted in this example in YYYYMMDD format.')) parser.add_argument( '--start_date', default=DEFAULT_START_DATE, type=valid_date, help=('The start date for the filter set\'s time_range field, which ' 'will be accepted in this example in YYYYMMDD format.')) # Optional fields. parser.add_argument( '-e', '--environment', required=False, type=environment_type, help=('The environment on which to filter.')) parser.add_argument( '-f', '--format', required=False, type=format_type, help=('The format on which to filter.')) parser.add_argument( '-p', '--platforms', required=False, nargs='*', type=platform_type, help=('The platforms on which to filter. The filters represented by ' 'multiple platforms are ORed together. Note that you may specify ' 'more than one using a space as a delimiter.')) parser.add_argument( '-s', '--seller_network_ids', required=False, nargs='*', type=int, help=('The list of IDs for seller networks on which to filter. The ' 'filters represented by multiple seller network IDs are ORed ' 'together. Note that you may specify more than one using a space ' 'as a delimiter.')) parser.add_argument( '-t', '--time_series_granularity', required=False, type=time_series_granularity_type, help=('The granularity of time intervals if a time series breakdown is ' 'desired.')) parser.add_argument( '--is_transient', required=False, default=True, type=bool, help=('Whether the filter set is transient, or should be persisted ' 'indefinitely. In this example, this will default to True.')) args = parser.parse_args() # Build the time_range as an AbsoluteDateRange. time_range = { 'startDate': { 'year': args.start_date.year, 'month': args.start_date.month, 'day': args.start_date.day }, 'endDate': { 'year': args.end_date.year, 'month': args.end_date.month, 'day': args.end_date.day } } # Create a body containing the required fields. BODY = { 'name': _FILTER_SET_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id, filtersets_resource_id=args.resource_id), # Note: You may alternatively specify relativeDateRange or # realtimeTimeRange. 'absoluteDateRange': time_range } # Add optional fields to body if specified. if args.environment: BODY['environment'] = args.environment if args.format: BODY['format'] = args.format if args.platforms: BODY['platforms'] = args.platforms if args.seller_network_ids: BODY['sellerNetworkIds'] = args.seller_network_ids if args.time_series_granularity: BODY['timeSeriesGranularity'] = args.time_series_granularity try: service = samples_util.GetService('v2beta1') except IOError as ex: print(f'Unable to create adexchangebuyer service - {ex}') print('Did you specify the key file in samples_util.py?') sys.exit(1) main(service, _OWNER_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id), BODY, args.is_transient)
if s not in _VALID_TIME_SERIES_GRANULARITIES: raise argparse.ArgumentTypeError('Invalid TimeSeriesGranularity ' f'specified: "{s}".') return s
identifier_body
create_bidder_level_filter_set.py
#!/usr/bin/python # # Copyright 2017 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. """This example creates a bidder-level filter set. A bidder-level filter set can be used to retrieve aggregated data for all Authorized Buyers accounts under the given bidder account, including the bidder account itself. """ import argparse from datetime import date from datetime import datetime from datetime import timedelta import os import pprint import sys import uuid sys.path.insert(0, os.path.abspath('..')) from googleapiclient.errors import HttpError import samples_util _DATE_FORMAT = '%Y%m%d' _FILTER_SET_NAME_TEMPLATE = ('bidders/{bidders_resource_id}/' 'filterSets/{filtersets_resource_id}') _OWNER_NAME_TEMPLATE = 'bidders/{bidders_resource_id}' _TODAY = date.today() _VALID_ENVIRONMENTS = ('WEB', 'APP') _VALID_FORMATS = ('DISPLAY', 'VIDEO') _VALID_PLATFORMS = ('DESKTOP', 'TABLET', 'MOBILE') _VALID_TIME_SERIES_GRANULARITIES = ('HOURLY', 'DAILY') DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE' DEFAULT_FILTER_SET_RESOURCE_ID = f'FilterSet_{uuid.uuid4()}' DEFAULT_END_DATE = _TODAY.strftime(_DATE_FORMAT) DEFAULT_START_DATE = (_TODAY - timedelta(days=7)).strftime( _DATE_FORMAT) def main(ad_exchange_buyer, owner_name, body, is_transient): try: # Construct and execute the request. filter_set = ad_exchange_buyer.bidders().filterSets().create( ownerName=owner_name, isTransient=is_transient, body=body).execute() print(f'FilterSet created for bidder: "{owner_name}".') pprint.pprint(filter_set) except HttpError as e: print(e) if __name__ == '__main__': def time_series_granularity_type(s): if s not in _VALID_TIME_SERIES_GRANULARITIES: raise argparse.ArgumentTypeError('Invalid TimeSeriesGranularity ' f'specified: "{s}".') return s def environment_type(s): if s not in _VALID_ENVIRONMENTS: raise argparse.ArgumentTypeError( f'Invalid Environment specified: "{s}".') return s def format_type(s): if s not in _VALID_FORMATS: raise argparse.ArgumentTypeError(f'Invalid Format specified: "{s}".') return s def platform_type(s): if s not in _VALID_PLATFORMS:
return s def valid_date(s): try: return datetime.strptime(s, _DATE_FORMAT).date() except ValueError: raise argparse.ArgumentTypeError(f'Invalid date specified: "{s}".') parser = argparse.ArgumentParser( description=('Creates a bidder-level filter set with the specified ' 'options.')) # Required fields. parser.add_argument( '-b', '--bidder_resource_id', default=DEFAULT_BIDDER_RESOURCE_ID, help=('The resource ID of the bidders resource for which the filter set ' 'is being created. This will be used to construct the ownerName ' 'used as a path parameter for filter set requests. For additional ' 'information on how to configure the ownerName path parameter, ' 'see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets/create' '#body.PATH_PARAMETERS.owner_name')) parser.add_argument( '-r', '--resource_id', default=DEFAULT_FILTER_SET_RESOURCE_ID, help=('The resource ID of the filter set. Note that this must be ' 'unique. This will be used to construct the filter set\'s name. ' 'For additional information on how to configure a filter set\'s ' 'name, see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets#FilterSet.FIELDS.name')) parser.add_argument( '--end_date', default=DEFAULT_END_DATE, type=valid_date, help=('The end date for the filter set\'s absoluteDateRange field, which ' 'will be accepted in this example in YYYYMMDD format.')) parser.add_argument( '--start_date', default=DEFAULT_START_DATE, type=valid_date, help=('The start date for the filter set\'s time_range field, which ' 'will be accepted in this example in YYYYMMDD format.')) # Optional fields. parser.add_argument( '-e', '--environment', required=False, type=environment_type, help=('The environment on which to filter.')) parser.add_argument( '-f', '--format', required=False, type=format_type, help=('The format on which to filter.')) parser.add_argument( '-p', '--platforms', required=False, nargs='*', type=platform_type, help=('The platforms on which to filter. The filters represented by ' 'multiple platforms are ORed together. Note that you may specify ' 'more than one using a space as a delimiter.')) parser.add_argument( '-s', '--seller_network_ids', required=False, nargs='*', type=int, help=('The list of IDs for seller networks on which to filter. The ' 'filters represented by multiple seller network IDs are ORed ' 'together. Note that you may specify more than one using a space ' 'as a delimiter.')) parser.add_argument( '-t', '--time_series_granularity', required=False, type=time_series_granularity_type, help=('The granularity of time intervals if a time series breakdown is ' 'desired.')) parser.add_argument( '--is_transient', required=False, default=True, type=bool, help=('Whether the filter set is transient, or should be persisted ' 'indefinitely. In this example, this will default to True.')) args = parser.parse_args() # Build the time_range as an AbsoluteDateRange. time_range = { 'startDate': { 'year': args.start_date.year, 'month': args.start_date.month, 'day': args.start_date.day }, 'endDate': { 'year': args.end_date.year, 'month': args.end_date.month, 'day': args.end_date.day } } # Create a body containing the required fields. BODY = { 'name': _FILTER_SET_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id, filtersets_resource_id=args.resource_id), # Note: You may alternatively specify relativeDateRange or # realtimeTimeRange. 'absoluteDateRange': time_range } # Add optional fields to body if specified. if args.environment: BODY['environment'] = args.environment if args.format: BODY['format'] = args.format if args.platforms: BODY['platforms'] = args.platforms if args.seller_network_ids: BODY['sellerNetworkIds'] = args.seller_network_ids if args.time_series_granularity: BODY['timeSeriesGranularity'] = args.time_series_granularity try: service = samples_util.GetService('v2beta1') except IOError as ex: print(f'Unable to create adexchangebuyer service - {ex}') print('Did you specify the key file in samples_util.py?') sys.exit(1) main(service, _OWNER_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id), BODY, args.is_transient)
raise argparse.ArgumentTypeError(f'Invalid Platform specified: "{s}".')
conditional_block
i18n_plural_pipe.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Pipe, PipeTransform} from '@angular/core'; import {getPluralCategory, NgLocalization} from '../i18n/localization'; import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; const _INTERPOLATION_REGEXP: RegExp = /#/g; /** * @ngModule CommonModule * @description * * Maps a value to a string that pluralizes the value according to locale rules. * * @usageNotes * * ### Example * * {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'} * * @publicApi */ @Pipe({name: 'i18nPlural', pure: true}) export class I18nPluralPipe implements PipeTransform { constructor(private _localization: NgLocalization) {} /** * @param value the number to be formatted * @param pluralMap an object that mimics the ICU format, see * http://userguide.icu-project.org/formatparse/messages. * @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by * default). */ transform(value: number, pluralMap: {[count: string]: string}, locale?: string): string { if (value == null) return ''; if (typeof pluralMap !== 'object' || pluralMap === null)
const key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale); return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString()); } }
{ throw invalidPipeArgumentError(I18nPluralPipe, pluralMap); }
conditional_block
i18n_plural_pipe.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Pipe, PipeTransform} from '@angular/core'; import {getPluralCategory, NgLocalization} from '../i18n/localization'; import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; const _INTERPOLATION_REGEXP: RegExp = /#/g; /** * @ngModule CommonModule * @description *
* ### Example * * {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'} * * @publicApi */ @Pipe({name: 'i18nPlural', pure: true}) export class I18nPluralPipe implements PipeTransform { constructor(private _localization: NgLocalization) {} /** * @param value the number to be formatted * @param pluralMap an object that mimics the ICU format, see * http://userguide.icu-project.org/formatparse/messages. * @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by * default). */ transform(value: number, pluralMap: {[count: string]: string}, locale?: string): string { if (value == null) return ''; if (typeof pluralMap !== 'object' || pluralMap === null) { throw invalidPipeArgumentError(I18nPluralPipe, pluralMap); } const key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale); return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString()); } }
* Maps a value to a string that pluralizes the value according to locale rules. * * @usageNotes *
random_line_split
i18n_plural_pipe.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Pipe, PipeTransform} from '@angular/core'; import {getPluralCategory, NgLocalization} from '../i18n/localization'; import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; const _INTERPOLATION_REGEXP: RegExp = /#/g; /** * @ngModule CommonModule * @description * * Maps a value to a string that pluralizes the value according to locale rules. * * @usageNotes * * ### Example * * {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'} * * @publicApi */ @Pipe({name: 'i18nPlural', pure: true}) export class I18nPluralPipe implements PipeTransform { constructor(private _localization: NgLocalization) {} /** * @param value the number to be formatted * @param pluralMap an object that mimics the ICU format, see * http://userguide.icu-project.org/formatparse/messages. * @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by * default). */
(value: number, pluralMap: {[count: string]: string}, locale?: string): string { if (value == null) return ''; if (typeof pluralMap !== 'object' || pluralMap === null) { throw invalidPipeArgumentError(I18nPluralPipe, pluralMap); } const key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale); return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString()); } }
transform
identifier_name
global-position-strategy.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {PositionStrategy} from './position-strategy'; import {OverlayRef} from '../overlay-ref'; /** * A strategy for positioning overlays. Using this strategy, an overlay is given an * explicit position relative to the browser's viewport. We use flexbox, instead of * transforms, in order to avoid issues with subpixel rendering which can cause the * element to become blurry. */ export class GlobalPositionStrategy implements PositionStrategy { /** The overlay to which this strategy is attached. */ private _overlayRef: OverlayRef; private _cssPosition: string = 'static'; private _topOffset: string = ''; private _bottomOffset: string = ''; private _leftOffset: string = ''; private _rightOffset: string = ''; private _alignItems: string = ''; private _justifyContent: string = ''; private _width: string = ''; private _height: string = ''; /* A lazily-created wrapper for the overlay element that is used as a flex container. */ private _wrapper: HTMLElement | null = null; constructor(private _document: any) {} attach(overlayRef: OverlayRef): void { this._overlayRef = overlayRef; } /** * Sets the top position of the overlay. Clears any previously set vertical position. * @param value New top offset. */ top(value: string = ''): this { this._bottomOffset = ''; this._topOffset = value; this._alignItems = 'flex-start'; return this; } /** * Sets the left position of the overlay. Clears any previously set horizontal position. * @param value New left offset. */ left(value: string = ''): this { this._rightOffset = ''; this._leftOffset = value; this._justifyContent = 'flex-start'; return this; } /** * Sets the bottom position of the overlay. Clears any previously set vertical position. * @param value New bottom offset. */ bottom(value: string = ''): this { this._topOffset = ''; this._bottomOffset = value; this._alignItems = 'flex-end'; return this; } /** * Sets the right position of the overlay. Clears any previously set horizontal position. * @param value New right offset. */ right(value: string = ''): this { this._leftOffset = ''; this._rightOffset = value; this._justifyContent = 'flex-end'; return this; } /** * Sets the overlay width and clears any previously set width. * @param value New width for the overlay */ width(value: string = ''): this { this._width = value; // When the width is 100%, we should reset the `left` and the offset, // in order to ensure that the element is flush against the viewport edge. if (value === '100%') { this.left('0px'); } return this; } /** * Sets the overlay height and clears any previously set height. * @param value New height for the overlay */ height(value: string = ''): this { this._height = value; // When the height is 100%, we should reset the `top` and the offset, // in order to ensure that the element is flush against the viewport edge. if (value === '100%') { this.top('0px'); } return this; } /** * Centers the overlay horizontally with an optional offset. * Clears any previously set horizontal position. * * @param offset Overlay offset from the horizontal center. */ centerHorizontally(offset: string = ''): this { this.left(offset); this._justifyContent = 'center'; return this; } /** * Centers the overlay vertically with an optional offset. * Clears any previously set vertical position. * * @param offset Overlay offset from the vertical center. */ centerVertically(offset: string = ''): this { this.top(offset); this._alignItems = 'center'; return this; } /** * Apply the position to the element. * @docs-private * * @returns Resolved when the styles have been applied. */ apply(): void { // Since the overlay ref applies the strategy asynchronously, it could // have been disposed before it ends up being applied. If that is the // case, we shouldn't do anything. if (!this._overlayRef.hasAttached()) { return; } const element = this._overlayRef.overlayElement;
this._wrapper!.appendChild(element); } let styles = element.style; let parentStyles = (element.parentNode as HTMLElement).style; styles.position = this._cssPosition; styles.marginTop = this._topOffset; styles.marginLeft = this._leftOffset; styles.marginBottom = this._bottomOffset; styles.marginRight = this._rightOffset; styles.width = this._width; styles.height = this._height; parentStyles.justifyContent = this._justifyContent; parentStyles.alignItems = this._alignItems; } /** Removes the wrapper element from the DOM. */ dispose(): void { if (this._wrapper && this._wrapper.parentNode) { this._wrapper.parentNode.removeChild(this._wrapper); this._wrapper = null; } } }
if (!this._wrapper && element.parentNode) { this._wrapper = this._document.createElement('div'); this._wrapper!.classList.add('cdk-global-overlay-wrapper'); element.parentNode.insertBefore(this._wrapper!, element);
random_line_split
global-position-strategy.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {PositionStrategy} from './position-strategy'; import {OverlayRef} from '../overlay-ref'; /** * A strategy for positioning overlays. Using this strategy, an overlay is given an * explicit position relative to the browser's viewport. We use flexbox, instead of * transforms, in order to avoid issues with subpixel rendering which can cause the * element to become blurry. */ export class GlobalPositionStrategy implements PositionStrategy { /** The overlay to which this strategy is attached. */ private _overlayRef: OverlayRef; private _cssPosition: string = 'static'; private _topOffset: string = ''; private _bottomOffset: string = ''; private _leftOffset: string = ''; private _rightOffset: string = ''; private _alignItems: string = ''; private _justifyContent: string = ''; private _width: string = ''; private _height: string = ''; /* A lazily-created wrapper for the overlay element that is used as a flex container. */ private _wrapper: HTMLElement | null = null; constructor(private _document: any) {} attach(overlayRef: OverlayRef): void { this._overlayRef = overlayRef; } /** * Sets the top position of the overlay. Clears any previously set vertical position. * @param value New top offset. */ top(value: string = ''): this { this._bottomOffset = ''; this._topOffset = value; this._alignItems = 'flex-start'; return this; } /** * Sets the left position of the overlay. Clears any previously set horizontal position. * @param value New left offset. */ left(value: string = ''): this { this._rightOffset = ''; this._leftOffset = value; this._justifyContent = 'flex-start'; return this; } /** * Sets the bottom position of the overlay. Clears any previously set vertical position. * @param value New bottom offset. */ bottom(value: string = ''): this { this._topOffset = ''; this._bottomOffset = value; this._alignItems = 'flex-end'; return this; } /** * Sets the right position of the overlay. Clears any previously set horizontal position. * @param value New right offset. */ right(value: string = ''): this { this._leftOffset = ''; this._rightOffset = value; this._justifyContent = 'flex-end'; return this; } /** * Sets the overlay width and clears any previously set width. * @param value New width for the overlay */ width(value: string = ''): this { this._width = value; // When the width is 100%, we should reset the `left` and the offset, // in order to ensure that the element is flush against the viewport edge. if (value === '100%') { this.left('0px'); } return this; } /** * Sets the overlay height and clears any previously set height. * @param value New height for the overlay */ height(value: string = ''): this { this._height = value; // When the height is 100%, we should reset the `top` and the offset, // in order to ensure that the element is flush against the viewport edge. if (value === '100%') { this.top('0px'); } return this; } /** * Centers the overlay horizontally with an optional offset. * Clears any previously set horizontal position. * * @param offset Overlay offset from the horizontal center. */ centerHorizontally(offset: string = ''): this { this.left(offset); this._justifyContent = 'center'; return this; } /** * Centers the overlay vertically with an optional offset. * Clears any previously set vertical position. * * @param offset Overlay offset from the vertical center. */ centerVertically(offset: string = ''): this { this.top(offset); this._alignItems = 'center'; return this; } /** * Apply the position to the element. * @docs-private * * @returns Resolved when the styles have been applied. */ apply(): void { // Since the overlay ref applies the strategy asynchronously, it could // have been disposed before it ends up being applied. If that is the // case, we shouldn't do anything. if (!this._overlayRef.hasAttached()) { return; } const element = this._overlayRef.overlayElement; if (!this._wrapper && element.parentNode)
let styles = element.style; let parentStyles = (element.parentNode as HTMLElement).style; styles.position = this._cssPosition; styles.marginTop = this._topOffset; styles.marginLeft = this._leftOffset; styles.marginBottom = this._bottomOffset; styles.marginRight = this._rightOffset; styles.width = this._width; styles.height = this._height; parentStyles.justifyContent = this._justifyContent; parentStyles.alignItems = this._alignItems; } /** Removes the wrapper element from the DOM. */ dispose(): void { if (this._wrapper && this._wrapper.parentNode) { this._wrapper.parentNode.removeChild(this._wrapper); this._wrapper = null; } } }
{ this._wrapper = this._document.createElement('div'); this._wrapper!.classList.add('cdk-global-overlay-wrapper'); element.parentNode.insertBefore(this._wrapper!, element); this._wrapper!.appendChild(element); }
conditional_block
global-position-strategy.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {PositionStrategy} from './position-strategy'; import {OverlayRef} from '../overlay-ref'; /** * A strategy for positioning overlays. Using this strategy, an overlay is given an * explicit position relative to the browser's viewport. We use flexbox, instead of * transforms, in order to avoid issues with subpixel rendering which can cause the * element to become blurry. */ export class
implements PositionStrategy { /** The overlay to which this strategy is attached. */ private _overlayRef: OverlayRef; private _cssPosition: string = 'static'; private _topOffset: string = ''; private _bottomOffset: string = ''; private _leftOffset: string = ''; private _rightOffset: string = ''; private _alignItems: string = ''; private _justifyContent: string = ''; private _width: string = ''; private _height: string = ''; /* A lazily-created wrapper for the overlay element that is used as a flex container. */ private _wrapper: HTMLElement | null = null; constructor(private _document: any) {} attach(overlayRef: OverlayRef): void { this._overlayRef = overlayRef; } /** * Sets the top position of the overlay. Clears any previously set vertical position. * @param value New top offset. */ top(value: string = ''): this { this._bottomOffset = ''; this._topOffset = value; this._alignItems = 'flex-start'; return this; } /** * Sets the left position of the overlay. Clears any previously set horizontal position. * @param value New left offset. */ left(value: string = ''): this { this._rightOffset = ''; this._leftOffset = value; this._justifyContent = 'flex-start'; return this; } /** * Sets the bottom position of the overlay. Clears any previously set vertical position. * @param value New bottom offset. */ bottom(value: string = ''): this { this._topOffset = ''; this._bottomOffset = value; this._alignItems = 'flex-end'; return this; } /** * Sets the right position of the overlay. Clears any previously set horizontal position. * @param value New right offset. */ right(value: string = ''): this { this._leftOffset = ''; this._rightOffset = value; this._justifyContent = 'flex-end'; return this; } /** * Sets the overlay width and clears any previously set width. * @param value New width for the overlay */ width(value: string = ''): this { this._width = value; // When the width is 100%, we should reset the `left` and the offset, // in order to ensure that the element is flush against the viewport edge. if (value === '100%') { this.left('0px'); } return this; } /** * Sets the overlay height and clears any previously set height. * @param value New height for the overlay */ height(value: string = ''): this { this._height = value; // When the height is 100%, we should reset the `top` and the offset, // in order to ensure that the element is flush against the viewport edge. if (value === '100%') { this.top('0px'); } return this; } /** * Centers the overlay horizontally with an optional offset. * Clears any previously set horizontal position. * * @param offset Overlay offset from the horizontal center. */ centerHorizontally(offset: string = ''): this { this.left(offset); this._justifyContent = 'center'; return this; } /** * Centers the overlay vertically with an optional offset. * Clears any previously set vertical position. * * @param offset Overlay offset from the vertical center. */ centerVertically(offset: string = ''): this { this.top(offset); this._alignItems = 'center'; return this; } /** * Apply the position to the element. * @docs-private * * @returns Resolved when the styles have been applied. */ apply(): void { // Since the overlay ref applies the strategy asynchronously, it could // have been disposed before it ends up being applied. If that is the // case, we shouldn't do anything. if (!this._overlayRef.hasAttached()) { return; } const element = this._overlayRef.overlayElement; if (!this._wrapper && element.parentNode) { this._wrapper = this._document.createElement('div'); this._wrapper!.classList.add('cdk-global-overlay-wrapper'); element.parentNode.insertBefore(this._wrapper!, element); this._wrapper!.appendChild(element); } let styles = element.style; let parentStyles = (element.parentNode as HTMLElement).style; styles.position = this._cssPosition; styles.marginTop = this._topOffset; styles.marginLeft = this._leftOffset; styles.marginBottom = this._bottomOffset; styles.marginRight = this._rightOffset; styles.width = this._width; styles.height = this._height; parentStyles.justifyContent = this._justifyContent; parentStyles.alignItems = this._alignItems; } /** Removes the wrapper element from the DOM. */ dispose(): void { if (this._wrapper && this._wrapper.parentNode) { this._wrapper.parentNode.removeChild(this._wrapper); this._wrapper = null; } } }
GlobalPositionStrategy
identifier_name
global-position-strategy.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {PositionStrategy} from './position-strategy'; import {OverlayRef} from '../overlay-ref'; /** * A strategy for positioning overlays. Using this strategy, an overlay is given an * explicit position relative to the browser's viewport. We use flexbox, instead of * transforms, in order to avoid issues with subpixel rendering which can cause the * element to become blurry. */ export class GlobalPositionStrategy implements PositionStrategy { /** The overlay to which this strategy is attached. */ private _overlayRef: OverlayRef; private _cssPosition: string = 'static'; private _topOffset: string = ''; private _bottomOffset: string = ''; private _leftOffset: string = ''; private _rightOffset: string = ''; private _alignItems: string = ''; private _justifyContent: string = ''; private _width: string = ''; private _height: string = ''; /* A lazily-created wrapper for the overlay element that is used as a flex container. */ private _wrapper: HTMLElement | null = null; constructor(private _document: any) {} attach(overlayRef: OverlayRef): void { this._overlayRef = overlayRef; } /** * Sets the top position of the overlay. Clears any previously set vertical position. * @param value New top offset. */ top(value: string = ''): this { this._bottomOffset = ''; this._topOffset = value; this._alignItems = 'flex-start'; return this; } /** * Sets the left position of the overlay. Clears any previously set horizontal position. * @param value New left offset. */ left(value: string = ''): this { this._rightOffset = ''; this._leftOffset = value; this._justifyContent = 'flex-start'; return this; } /** * Sets the bottom position of the overlay. Clears any previously set vertical position. * @param value New bottom offset. */ bottom(value: string = ''): this { this._topOffset = ''; this._bottomOffset = value; this._alignItems = 'flex-end'; return this; } /** * Sets the right position of the overlay. Clears any previously set horizontal position. * @param value New right offset. */ right(value: string = ''): this { this._leftOffset = ''; this._rightOffset = value; this._justifyContent = 'flex-end'; return this; } /** * Sets the overlay width and clears any previously set width. * @param value New width for the overlay */ width(value: string = ''): this { this._width = value; // When the width is 100%, we should reset the `left` and the offset, // in order to ensure that the element is flush against the viewport edge. if (value === '100%') { this.left('0px'); } return this; } /** * Sets the overlay height and clears any previously set height. * @param value New height for the overlay */ height(value: string = ''): this
/** * Centers the overlay horizontally with an optional offset. * Clears any previously set horizontal position. * * @param offset Overlay offset from the horizontal center. */ centerHorizontally(offset: string = ''): this { this.left(offset); this._justifyContent = 'center'; return this; } /** * Centers the overlay vertically with an optional offset. * Clears any previously set vertical position. * * @param offset Overlay offset from the vertical center. */ centerVertically(offset: string = ''): this { this.top(offset); this._alignItems = 'center'; return this; } /** * Apply the position to the element. * @docs-private * * @returns Resolved when the styles have been applied. */ apply(): void { // Since the overlay ref applies the strategy asynchronously, it could // have been disposed before it ends up being applied. If that is the // case, we shouldn't do anything. if (!this._overlayRef.hasAttached()) { return; } const element = this._overlayRef.overlayElement; if (!this._wrapper && element.parentNode) { this._wrapper = this._document.createElement('div'); this._wrapper!.classList.add('cdk-global-overlay-wrapper'); element.parentNode.insertBefore(this._wrapper!, element); this._wrapper!.appendChild(element); } let styles = element.style; let parentStyles = (element.parentNode as HTMLElement).style; styles.position = this._cssPosition; styles.marginTop = this._topOffset; styles.marginLeft = this._leftOffset; styles.marginBottom = this._bottomOffset; styles.marginRight = this._rightOffset; styles.width = this._width; styles.height = this._height; parentStyles.justifyContent = this._justifyContent; parentStyles.alignItems = this._alignItems; } /** Removes the wrapper element from the DOM. */ dispose(): void { if (this._wrapper && this._wrapper.parentNode) { this._wrapper.parentNode.removeChild(this._wrapper); this._wrapper = null; } } }
{ this._height = value; // When the height is 100%, we should reset the `top` and the offset, // in order to ensure that the element is flush against the viewport edge. if (value === '100%') { this.top('0px'); } return this; }
identifier_body
offlinequeue.py
# -*- coding: utf-8 -*- """ wakatime.offlinequeue ~~~~~~~~~~~~~~~~~~~~~ Queue for saving heartbeats while offline. :copyright: (c) 2014 Alan Hamlett. :license: BSD, see LICENSE for more details. """ import logging import os from time import sleep from .compat import json from .constants import DEFAULT_SYNC_OFFLINE_ACTIVITY, HEARTBEATS_PER_REQUEST from .heartbeat import Heartbeat try: import sqlite3 HAS_SQL = True except ImportError: # pragma: nocover HAS_SQL = False log = logging.getLogger('WakaTime') class Queue(object):
if not HAS_SQL: return try: conn, c = self.connect() data = { 'id': heartbeat.get_id(), 'heartbeat': heartbeat.json(), } c.execute('INSERT INTO {0} VALUES (:id,:heartbeat)'.format(self.table_name), data) conn.commit() conn.close() except sqlite3.Error: log.traceback() def pop(self): if not HAS_SQL: return None tries = 3 wait = 0.1 try: conn, c = self.connect() except sqlite3.Error: log.traceback(logging.DEBUG) return None heartbeat = None loop = True while loop and tries > -1: try: c.execute('BEGIN IMMEDIATE') c.execute('SELECT * FROM {0} LIMIT 1'.format(self.table_name)) row = c.fetchone() if row is not None: id = row[0] heartbeat = Heartbeat(json.loads(row[1]), self.args, self.configs, _clone=True) c.execute('DELETE FROM {0} WHERE id=?'.format(self.table_name), [id]) conn.commit() loop = False except sqlite3.Error: log.traceback(logging.DEBUG) sleep(wait) tries -= 1 try: conn.close() except sqlite3.Error: log.traceback(logging.DEBUG) return heartbeat def push_many(self, heartbeats): for heartbeat in heartbeats: self.push(heartbeat) def pop_many(self, limit=None): if limit is None: limit = DEFAULT_SYNC_OFFLINE_ACTIVITY heartbeats = [] count = 0 while count < limit: heartbeat = self.pop() if not heartbeat: break heartbeats.append(heartbeat) count += 1 if count % HEARTBEATS_PER_REQUEST == 0: yield heartbeats heartbeats = [] if heartbeats: yield heartbeats def _get_db_file(self): home = '~' if os.environ.get('WAKATIME_HOME'): home = os.environ.get('WAKATIME_HOME') return os.path.join(os.path.expanduser(home), '.wakatime.db')
db_file = '.wakatime.db' table_name = 'heartbeat_2' args = None configs = None def __init__(self, args, configs): self.args = args self.configs = configs def connect(self): conn = sqlite3.connect(self._get_db_file(), isolation_level=None) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS {0} ( id text, heartbeat text) '''.format(self.table_name)) return (conn, c) def push(self, heartbeat):
identifier_body
offlinequeue.py
# -*- coding: utf-8 -*- """ wakatime.offlinequeue ~~~~~~~~~~~~~~~~~~~~~ Queue for saving heartbeats while offline. :copyright: (c) 2014 Alan Hamlett. :license: BSD, see LICENSE for more details. """ import logging import os from time import sleep from .compat import json from .constants import DEFAULT_SYNC_OFFLINE_ACTIVITY, HEARTBEATS_PER_REQUEST from .heartbeat import Heartbeat try: import sqlite3 HAS_SQL = True except ImportError: # pragma: nocover HAS_SQL = False log = logging.getLogger('WakaTime') class
(object): db_file = '.wakatime.db' table_name = 'heartbeat_2' args = None configs = None def __init__(self, args, configs): self.args = args self.configs = configs def connect(self): conn = sqlite3.connect(self._get_db_file(), isolation_level=None) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS {0} ( id text, heartbeat text) '''.format(self.table_name)) return (conn, c) def push(self, heartbeat): if not HAS_SQL: return try: conn, c = self.connect() data = { 'id': heartbeat.get_id(), 'heartbeat': heartbeat.json(), } c.execute('INSERT INTO {0} VALUES (:id,:heartbeat)'.format(self.table_name), data) conn.commit() conn.close() except sqlite3.Error: log.traceback() def pop(self): if not HAS_SQL: return None tries = 3 wait = 0.1 try: conn, c = self.connect() except sqlite3.Error: log.traceback(logging.DEBUG) return None heartbeat = None loop = True while loop and tries > -1: try: c.execute('BEGIN IMMEDIATE') c.execute('SELECT * FROM {0} LIMIT 1'.format(self.table_name)) row = c.fetchone() if row is not None: id = row[0] heartbeat = Heartbeat(json.loads(row[1]), self.args, self.configs, _clone=True) c.execute('DELETE FROM {0} WHERE id=?'.format(self.table_name), [id]) conn.commit() loop = False except sqlite3.Error: log.traceback(logging.DEBUG) sleep(wait) tries -= 1 try: conn.close() except sqlite3.Error: log.traceback(logging.DEBUG) return heartbeat def push_many(self, heartbeats): for heartbeat in heartbeats: self.push(heartbeat) def pop_many(self, limit=None): if limit is None: limit = DEFAULT_SYNC_OFFLINE_ACTIVITY heartbeats = [] count = 0 while count < limit: heartbeat = self.pop() if not heartbeat: break heartbeats.append(heartbeat) count += 1 if count % HEARTBEATS_PER_REQUEST == 0: yield heartbeats heartbeats = [] if heartbeats: yield heartbeats def _get_db_file(self): home = '~' if os.environ.get('WAKATIME_HOME'): home = os.environ.get('WAKATIME_HOME') return os.path.join(os.path.expanduser(home), '.wakatime.db')
Queue
identifier_name
offlinequeue.py
# -*- coding: utf-8 -*- """ wakatime.offlinequeue ~~~~~~~~~~~~~~~~~~~~~ Queue for saving heartbeats while offline. :copyright: (c) 2014 Alan Hamlett. :license: BSD, see LICENSE for more details. """ import logging import os from time import sleep from .compat import json from .constants import DEFAULT_SYNC_OFFLINE_ACTIVITY, HEARTBEATS_PER_REQUEST from .heartbeat import Heartbeat try: import sqlite3 HAS_SQL = True except ImportError: # pragma: nocover HAS_SQL = False log = logging.getLogger('WakaTime') class Queue(object): db_file = '.wakatime.db' table_name = 'heartbeat_2' args = None configs = None def __init__(self, args, configs): self.args = args self.configs = configs def connect(self): conn = sqlite3.connect(self._get_db_file(), isolation_level=None) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS {0} ( id text, heartbeat text) '''.format(self.table_name)) return (conn, c) def push(self, heartbeat): if not HAS_SQL: return try: conn, c = self.connect() data = { 'id': heartbeat.get_id(), 'heartbeat': heartbeat.json(), } c.execute('INSERT INTO {0} VALUES (:id,:heartbeat)'.format(self.table_name), data) conn.commit() conn.close() except sqlite3.Error: log.traceback() def pop(self): if not HAS_SQL: return None tries = 3 wait = 0.1 try: conn, c = self.connect() except sqlite3.Error: log.traceback(logging.DEBUG) return None heartbeat = None loop = True while loop and tries > -1: try:
c.execute('SELECT * FROM {0} LIMIT 1'.format(self.table_name)) row = c.fetchone() if row is not None: id = row[0] heartbeat = Heartbeat(json.loads(row[1]), self.args, self.configs, _clone=True) c.execute('DELETE FROM {0} WHERE id=?'.format(self.table_name), [id]) conn.commit() loop = False except sqlite3.Error: log.traceback(logging.DEBUG) sleep(wait) tries -= 1 try: conn.close() except sqlite3.Error: log.traceback(logging.DEBUG) return heartbeat def push_many(self, heartbeats): for heartbeat in heartbeats: self.push(heartbeat) def pop_many(self, limit=None): if limit is None: limit = DEFAULT_SYNC_OFFLINE_ACTIVITY heartbeats = [] count = 0 while count < limit: heartbeat = self.pop() if not heartbeat: break heartbeats.append(heartbeat) count += 1 if count % HEARTBEATS_PER_REQUEST == 0: yield heartbeats heartbeats = [] if heartbeats: yield heartbeats def _get_db_file(self): home = '~' if os.environ.get('WAKATIME_HOME'): home = os.environ.get('WAKATIME_HOME') return os.path.join(os.path.expanduser(home), '.wakatime.db')
c.execute('BEGIN IMMEDIATE')
random_line_split
offlinequeue.py
# -*- coding: utf-8 -*- """ wakatime.offlinequeue ~~~~~~~~~~~~~~~~~~~~~ Queue for saving heartbeats while offline. :copyright: (c) 2014 Alan Hamlett. :license: BSD, see LICENSE for more details. """ import logging import os from time import sleep from .compat import json from .constants import DEFAULT_SYNC_OFFLINE_ACTIVITY, HEARTBEATS_PER_REQUEST from .heartbeat import Heartbeat try: import sqlite3 HAS_SQL = True except ImportError: # pragma: nocover HAS_SQL = False log = logging.getLogger('WakaTime') class Queue(object): db_file = '.wakatime.db' table_name = 'heartbeat_2' args = None configs = None def __init__(self, args, configs): self.args = args self.configs = configs def connect(self): conn = sqlite3.connect(self._get_db_file(), isolation_level=None) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS {0} ( id text, heartbeat text) '''.format(self.table_name)) return (conn, c) def push(self, heartbeat): if not HAS_SQL: return try: conn, c = self.connect() data = { 'id': heartbeat.get_id(), 'heartbeat': heartbeat.json(), } c.execute('INSERT INTO {0} VALUES (:id,:heartbeat)'.format(self.table_name), data) conn.commit() conn.close() except sqlite3.Error: log.traceback() def pop(self): if not HAS_SQL: return None tries = 3 wait = 0.1 try: conn, c = self.connect() except sqlite3.Error: log.traceback(logging.DEBUG) return None heartbeat = None loop = True while loop and tries > -1: try: c.execute('BEGIN IMMEDIATE') c.execute('SELECT * FROM {0} LIMIT 1'.format(self.table_name)) row = c.fetchone() if row is not None: id = row[0] heartbeat = Heartbeat(json.loads(row[1]), self.args, self.configs, _clone=True) c.execute('DELETE FROM {0} WHERE id=?'.format(self.table_name), [id]) conn.commit() loop = False except sqlite3.Error: log.traceback(logging.DEBUG) sleep(wait) tries -= 1 try: conn.close() except sqlite3.Error: log.traceback(logging.DEBUG) return heartbeat def push_many(self, heartbeats): for heartbeat in heartbeats: self.push(heartbeat) def pop_many(self, limit=None): if limit is None:
heartbeats = [] count = 0 while count < limit: heartbeat = self.pop() if not heartbeat: break heartbeats.append(heartbeat) count += 1 if count % HEARTBEATS_PER_REQUEST == 0: yield heartbeats heartbeats = [] if heartbeats: yield heartbeats def _get_db_file(self): home = '~' if os.environ.get('WAKATIME_HOME'): home = os.environ.get('WAKATIME_HOME') return os.path.join(os.path.expanduser(home), '.wakatime.db')
limit = DEFAULT_SYNC_OFFLINE_ACTIVITY
conditional_block
items.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from viaspider.settings import SUMMARY_LIMIT class ViaspiderItem(scrapy.Item): # define the fields for your item here like: url = scrapy.Field() title = scrapy.Field() summary = scrapy.Field() categories = scrapy.Field() tags = scrapy.Field() image = scrapy.Field() source = scrapy.Field() created = scrapy.Field() class ItemParser(object):
result = self.response.xpath('//head/meta[@property="og:description"]/@content').extract()[0] return result[:-(SUMMARY_LIMIT + 3)] + '...' if len(result) > SUMMARY_LIMIT else result @property def categories(self): results = self.response.xpath('//head/meta[@property="article:section"]/@content').extract() return results @property def tags(self): results = self.response.xpath('//head/meta[@property="article:tag"]/@content').extract() return results if len(results) > 0 else self.categories @property def image(self): result = self.response.xpath('//head/meta[@property="og:image"]/@content').extract()[0] return result @property def created(self): result = self.response.xpath('//head/meta[@property="article:published_time"]/@content').extract()[0] return result def parse(self): item = ViaspiderItem() item['url'] = self.url item['source'] = self.source item['title'] = self.title item['summary'] = self.summary item['categories'] = self.categories item['tags'] = self.tags item['image'] = self.image item['created'] = self.created return item
def __init__(self, source, response, seperator, bloginfo): self.source = source self.response = response self.seperator = seperator self.bloginfo = " " + self.seperator + " " + bloginfo @property def url(self): return self.response.url @property def title(self): result = self.response.xpath('//head/title/text()').extract()[0].encode('utf-8') if result.endswith(self.bloginfo): return (self.seperator.join(result.split(self.seperator)[:-1])).strip() else: return result @property def summary(self):
identifier_body
items.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from viaspider.settings import SUMMARY_LIMIT class ViaspiderItem(scrapy.Item): # define the fields for your item here like: url = scrapy.Field() title = scrapy.Field() summary = scrapy.Field() categories = scrapy.Field() tags = scrapy.Field() image = scrapy.Field() source = scrapy.Field() created = scrapy.Field()
self.bloginfo = " " + self.seperator + " " + bloginfo @property def url(self): return self.response.url @property def title(self): result = self.response.xpath('//head/title/text()').extract()[0].encode('utf-8') if result.endswith(self.bloginfo): return (self.seperator.join(result.split(self.seperator)[:-1])).strip() else: return result @property def summary(self): result = self.response.xpath('//head/meta[@property="og:description"]/@content').extract()[0] return result[:-(SUMMARY_LIMIT + 3)] + '...' if len(result) > SUMMARY_LIMIT else result @property def categories(self): results = self.response.xpath('//head/meta[@property="article:section"]/@content').extract() return results @property def tags(self): results = self.response.xpath('//head/meta[@property="article:tag"]/@content').extract() return results if len(results) > 0 else self.categories @property def image(self): result = self.response.xpath('//head/meta[@property="og:image"]/@content').extract()[0] return result @property def created(self): result = self.response.xpath('//head/meta[@property="article:published_time"]/@content').extract()[0] return result def parse(self): item = ViaspiderItem() item['url'] = self.url item['source'] = self.source item['title'] = self.title item['summary'] = self.summary item['categories'] = self.categories item['tags'] = self.tags item['image'] = self.image item['created'] = self.created return item
class ItemParser(object): def __init__(self, source, response, seperator, bloginfo): self.source = source self.response = response self.seperator = seperator
random_line_split
items.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from viaspider.settings import SUMMARY_LIMIT class ViaspiderItem(scrapy.Item): # define the fields for your item here like: url = scrapy.Field() title = scrapy.Field() summary = scrapy.Field() categories = scrapy.Field() tags = scrapy.Field() image = scrapy.Field() source = scrapy.Field() created = scrapy.Field() class ItemParser(object): def __init__(self, source, response, seperator, bloginfo): self.source = source self.response = response self.seperator = seperator self.bloginfo = " " + self.seperator + " " + bloginfo @property def url(self): return self.response.url @property def title(self): result = self.response.xpath('//head/title/text()').extract()[0].encode('utf-8') if result.endswith(self.bloginfo): return (self.seperator.join(result.split(self.seperator)[:-1])).strip() else:
@property def summary(self): result = self.response.xpath('//head/meta[@property="og:description"]/@content').extract()[0] return result[:-(SUMMARY_LIMIT + 3)] + '...' if len(result) > SUMMARY_LIMIT else result @property def categories(self): results = self.response.xpath('//head/meta[@property="article:section"]/@content').extract() return results @property def tags(self): results = self.response.xpath('//head/meta[@property="article:tag"]/@content').extract() return results if len(results) > 0 else self.categories @property def image(self): result = self.response.xpath('//head/meta[@property="og:image"]/@content').extract()[0] return result @property def created(self): result = self.response.xpath('//head/meta[@property="article:published_time"]/@content').extract()[0] return result def parse(self): item = ViaspiderItem() item['url'] = self.url item['source'] = self.source item['title'] = self.title item['summary'] = self.summary item['categories'] = self.categories item['tags'] = self.tags item['image'] = self.image item['created'] = self.created return item
return result
conditional_block