body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
---|---|---|---|---|---|---|---|---|---|
eab3b5c834ed5579e933e9ecca2339f41ee602e6d77a2e4f4220e427d754ec92
|
async def async_configure(self, flow_id: str, user_input: Optional[Dict]=None) -> Any:
'Continue a configuration flow.'
flow = self._progress.get(flow_id)
if (flow is None):
raise UnknownFlow
cur_step = flow.cur_step
if ((cur_step.get('data_schema') is not None) and (user_input is not None)):
user_input = cur_step['data_schema'](user_input)
result = (await self._async_handle_step(flow, cur_step['step_id'], user_input))
if (cur_step['type'] == RESULT_TYPE_EXTERNAL_STEP):
if (result['type'] not in (RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_EXTERNAL_STEP_DONE)):
raise ValueError('External step can only transition to external step or external step done.')
if (cur_step['step_id'] != result.get('step_id')):
self.hass.bus.async_fire(EVENT_DATA_ENTRY_FLOW_PROGRESSED, {'handler': flow.handler, 'flow_id': flow_id, 'refresh': True})
return result
|
Continue a configuration flow.
|
homeassistant/data_entry_flow.py
|
async_configure
|
mockersf/home-assistant
| 23 |
python
|
async def async_configure(self, flow_id: str, user_input: Optional[Dict]=None) -> Any:
flow = self._progress.get(flow_id)
if (flow is None):
raise UnknownFlow
cur_step = flow.cur_step
if ((cur_step.get('data_schema') is not None) and (user_input is not None)):
user_input = cur_step['data_schema'](user_input)
result = (await self._async_handle_step(flow, cur_step['step_id'], user_input))
if (cur_step['type'] == RESULT_TYPE_EXTERNAL_STEP):
if (result['type'] not in (RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_EXTERNAL_STEP_DONE)):
raise ValueError('External step can only transition to external step or external step done.')
if (cur_step['step_id'] != result.get('step_id')):
self.hass.bus.async_fire(EVENT_DATA_ENTRY_FLOW_PROGRESSED, {'handler': flow.handler, 'flow_id': flow_id, 'refresh': True})
return result
|
async def async_configure(self, flow_id: str, user_input: Optional[Dict]=None) -> Any:
flow = self._progress.get(flow_id)
if (flow is None):
raise UnknownFlow
cur_step = flow.cur_step
if ((cur_step.get('data_schema') is not None) and (user_input is not None)):
user_input = cur_step['data_schema'](user_input)
result = (await self._async_handle_step(flow, cur_step['step_id'], user_input))
if (cur_step['type'] == RESULT_TYPE_EXTERNAL_STEP):
if (result['type'] not in (RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_EXTERNAL_STEP_DONE)):
raise ValueError('External step can only transition to external step or external step done.')
if (cur_step['step_id'] != result.get('step_id')):
self.hass.bus.async_fire(EVENT_DATA_ENTRY_FLOW_PROGRESSED, {'handler': flow.handler, 'flow_id': flow_id, 'refresh': True})
return result<|docstring|>Continue a configuration flow.<|endoftext|>
|
9d793ee9ef0b3bc665215f7d4d714da81fda6a282c63b9777ae9bdc55e430dae
|
@callback
def async_abort(self, flow_id: str) -> None:
'Abort a flow.'
if (self._progress.pop(flow_id, None) is None):
raise UnknownFlow
|
Abort a flow.
|
homeassistant/data_entry_flow.py
|
async_abort
|
mockersf/home-assistant
| 23 |
python
|
@callback
def async_abort(self, flow_id: str) -> None:
if (self._progress.pop(flow_id, None) is None):
raise UnknownFlow
|
@callback
def async_abort(self, flow_id: str) -> None:
if (self._progress.pop(flow_id, None) is None):
raise UnknownFlow<|docstring|>Abort a flow.<|endoftext|>
|
1bb15bb37211ad01b5c16c06e6fca0e7dc2ffd781730ca4c2cd20a62aef9a539
|
async def _async_handle_step(self, flow: Any, step_id: str, user_input: Optional[Dict]) -> Dict:
'Handle a step of a flow.'
method = f'async_step_{step_id}'
if (not hasattr(flow, method)):
self._progress.pop(flow.flow_id)
raise UnknownStep("Handler {} doesn't support step {}".format(flow.__class__.__name__, step_id))
try:
result: Dict = (await getattr(flow, method)(user_input))
except AbortFlow as err:
result = _create_abort_data(flow.flow_id, flow.handler, err.reason, err.description_placeholders)
if (result['type'] not in (RESULT_TYPE_FORM, RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_ABORT, RESULT_TYPE_EXTERNAL_STEP_DONE)):
raise ValueError('Handler returned incorrect type: {}'.format(result['type']))
if (result['type'] in (RESULT_TYPE_FORM, RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_EXTERNAL_STEP_DONE)):
flow.cur_step = result
return result
result = (await self._async_finish_flow(flow, dict(result)))
if (result['type'] == RESULT_TYPE_FORM):
flow.cur_step = result
return result
self._progress.pop(flow.flow_id)
return result
|
Handle a step of a flow.
|
homeassistant/data_entry_flow.py
|
_async_handle_step
|
mockersf/home-assistant
| 23 |
python
|
async def _async_handle_step(self, flow: Any, step_id: str, user_input: Optional[Dict]) -> Dict:
method = f'async_step_{step_id}'
if (not hasattr(flow, method)):
self._progress.pop(flow.flow_id)
raise UnknownStep("Handler {} doesn't support step {}".format(flow.__class__.__name__, step_id))
try:
result: Dict = (await getattr(flow, method)(user_input))
except AbortFlow as err:
result = _create_abort_data(flow.flow_id, flow.handler, err.reason, err.description_placeholders)
if (result['type'] not in (RESULT_TYPE_FORM, RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_ABORT, RESULT_TYPE_EXTERNAL_STEP_DONE)):
raise ValueError('Handler returned incorrect type: {}'.format(result['type']))
if (result['type'] in (RESULT_TYPE_FORM, RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_EXTERNAL_STEP_DONE)):
flow.cur_step = result
return result
result = (await self._async_finish_flow(flow, dict(result)))
if (result['type'] == RESULT_TYPE_FORM):
flow.cur_step = result
return result
self._progress.pop(flow.flow_id)
return result
|
async def _async_handle_step(self, flow: Any, step_id: str, user_input: Optional[Dict]) -> Dict:
method = f'async_step_{step_id}'
if (not hasattr(flow, method)):
self._progress.pop(flow.flow_id)
raise UnknownStep("Handler {} doesn't support step {}".format(flow.__class__.__name__, step_id))
try:
result: Dict = (await getattr(flow, method)(user_input))
except AbortFlow as err:
result = _create_abort_data(flow.flow_id, flow.handler, err.reason, err.description_placeholders)
if (result['type'] not in (RESULT_TYPE_FORM, RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_ABORT, RESULT_TYPE_EXTERNAL_STEP_DONE)):
raise ValueError('Handler returned incorrect type: {}'.format(result['type']))
if (result['type'] in (RESULT_TYPE_FORM, RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_EXTERNAL_STEP_DONE)):
flow.cur_step = result
return result
result = (await self._async_finish_flow(flow, dict(result)))
if (result['type'] == RESULT_TYPE_FORM):
flow.cur_step = result
return result
self._progress.pop(flow.flow_id)
return result<|docstring|>Handle a step of a flow.<|endoftext|>
|
7bd3f55b34f5663ed81796ea4961eb6df0ca7fad2ff904c691bd6a4d7719a503
|
@callback
def async_show_form(self, *, step_id: str, data_schema: vol.Schema=None, errors: Optional[Dict]=None, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
'Return the definition of a form to gather user input.'
return {'type': RESULT_TYPE_FORM, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': step_id, 'data_schema': data_schema, 'errors': errors, 'description_placeholders': description_placeholders}
|
Return the definition of a form to gather user input.
|
homeassistant/data_entry_flow.py
|
async_show_form
|
mockersf/home-assistant
| 23 |
python
|
@callback
def async_show_form(self, *, step_id: str, data_schema: vol.Schema=None, errors: Optional[Dict]=None, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
return {'type': RESULT_TYPE_FORM, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': step_id, 'data_schema': data_schema, 'errors': errors, 'description_placeholders': description_placeholders}
|
@callback
def async_show_form(self, *, step_id: str, data_schema: vol.Schema=None, errors: Optional[Dict]=None, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
return {'type': RESULT_TYPE_FORM, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': step_id, 'data_schema': data_schema, 'errors': errors, 'description_placeholders': description_placeholders}<|docstring|>Return the definition of a form to gather user input.<|endoftext|>
|
e4d194e3c8203c73ede8951c0c43f76d0e751143601d6816b2f9171f175ecaf6
|
@callback
def async_create_entry(self, *, title: str, data: Dict, description: Optional[str]=None, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
'Finish config flow and create a config entry.'
return {'version': self.VERSION, 'type': RESULT_TYPE_CREATE_ENTRY, 'flow_id': self.flow_id, 'handler': self.handler, 'title': title, 'data': data, 'description': description, 'description_placeholders': description_placeholders}
|
Finish config flow and create a config entry.
|
homeassistant/data_entry_flow.py
|
async_create_entry
|
mockersf/home-assistant
| 23 |
python
|
@callback
def async_create_entry(self, *, title: str, data: Dict, description: Optional[str]=None, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
return {'version': self.VERSION, 'type': RESULT_TYPE_CREATE_ENTRY, 'flow_id': self.flow_id, 'handler': self.handler, 'title': title, 'data': data, 'description': description, 'description_placeholders': description_placeholders}
|
@callback
def async_create_entry(self, *, title: str, data: Dict, description: Optional[str]=None, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
return {'version': self.VERSION, 'type': RESULT_TYPE_CREATE_ENTRY, 'flow_id': self.flow_id, 'handler': self.handler, 'title': title, 'data': data, 'description': description, 'description_placeholders': description_placeholders}<|docstring|>Finish config flow and create a config entry.<|endoftext|>
|
320b0f7f262795dcae93dc2b132767d979fb470cee4e72a518ea0535492e6a6d
|
@callback
def async_abort(self, *, reason: str, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
'Abort the config flow.'
return _create_abort_data(self.flow_id, cast(str, self.handler), reason, description_placeholders)
|
Abort the config flow.
|
homeassistant/data_entry_flow.py
|
async_abort
|
mockersf/home-assistant
| 23 |
python
|
@callback
def async_abort(self, *, reason: str, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
return _create_abort_data(self.flow_id, cast(str, self.handler), reason, description_placeholders)
|
@callback
def async_abort(self, *, reason: str, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
return _create_abort_data(self.flow_id, cast(str, self.handler), reason, description_placeholders)<|docstring|>Abort the config flow.<|endoftext|>
|
63d6a0a4e6b630d1072a8188d1b187aa93732e46c812aa519a488f6ed2216eab
|
@callback
def async_external_step(self, *, step_id: str, url: str, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
'Return the definition of an external step for the user to take.'
return {'type': RESULT_TYPE_EXTERNAL_STEP, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': step_id, 'url': url, 'description_placeholders': description_placeholders}
|
Return the definition of an external step for the user to take.
|
homeassistant/data_entry_flow.py
|
async_external_step
|
mockersf/home-assistant
| 23 |
python
|
@callback
def async_external_step(self, *, step_id: str, url: str, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
return {'type': RESULT_TYPE_EXTERNAL_STEP, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': step_id, 'url': url, 'description_placeholders': description_placeholders}
|
@callback
def async_external_step(self, *, step_id: str, url: str, description_placeholders: Optional[Dict]=None) -> Dict[(str, Any)]:
return {'type': RESULT_TYPE_EXTERNAL_STEP, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': step_id, 'url': url, 'description_placeholders': description_placeholders}<|docstring|>Return the definition of an external step for the user to take.<|endoftext|>
|
5dceb00c841d5ec198a570e59c2251378f6dd1b60a40c66b7354453078685045
|
@callback
def async_external_step_done(self, *, next_step_id: str) -> Dict[(str, Any)]:
'Return the definition of an external step for the user to take.'
return {'type': RESULT_TYPE_EXTERNAL_STEP_DONE, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': next_step_id}
|
Return the definition of an external step for the user to take.
|
homeassistant/data_entry_flow.py
|
async_external_step_done
|
mockersf/home-assistant
| 23 |
python
|
@callback
def async_external_step_done(self, *, next_step_id: str) -> Dict[(str, Any)]:
return {'type': RESULT_TYPE_EXTERNAL_STEP_DONE, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': next_step_id}
|
@callback
def async_external_step_done(self, *, next_step_id: str) -> Dict[(str, Any)]:
return {'type': RESULT_TYPE_EXTERNAL_STEP_DONE, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': next_step_id}<|docstring|>Return the definition of an external step for the user to take.<|endoftext|>
|
20ceecc44e9ab27e8b940f03b87bc9bffcf9d97ce4ddef136d4424f094b8786d
|
def create(self, context):
'Create a Deployable record in the DB.'
if ('uuid' not in self):
raise exception.ObjectActionError(action='create', reason='uuid is required')
if (self.parent_uuid is None):
self.root_uuid = self.uuid
else:
self.root_uuid = self._get_parent_root_uuid()
values = self.obj_get_changes()
db_dep = self.dbapi.deployable_create(context, values)
self._from_db_object(self, db_dep)
|
Create a Deployable record in the DB.
|
cyborg/objects/deployable.py
|
create
|
BobzhouCH/cyborg-acc
| 1 |
python
|
def create(self, context):
if ('uuid' not in self):
raise exception.ObjectActionError(action='create', reason='uuid is required')
if (self.parent_uuid is None):
self.root_uuid = self.uuid
else:
self.root_uuid = self._get_parent_root_uuid()
values = self.obj_get_changes()
db_dep = self.dbapi.deployable_create(context, values)
self._from_db_object(self, db_dep)
|
def create(self, context):
if ('uuid' not in self):
raise exception.ObjectActionError(action='create', reason='uuid is required')
if (self.parent_uuid is None):
self.root_uuid = self.uuid
else:
self.root_uuid = self._get_parent_root_uuid()
values = self.obj_get_changes()
db_dep = self.dbapi.deployable_create(context, values)
self._from_db_object(self, db_dep)<|docstring|>Create a Deployable record in the DB.<|endoftext|>
|
81c9a2afa71494bdcadc1c1d19d2c3b8c00c201f2b53d8e9a46d00e20f23ca8b
|
@classmethod
def get(cls, context, uuid):
'Find a DB Deployable and return an Obj Deployable.'
db_dep = cls.dbapi.deployable_get(context, uuid)
obj_dep = cls._from_db_object(cls(context), db_dep)
return obj_dep
|
Find a DB Deployable and return an Obj Deployable.
|
cyborg/objects/deployable.py
|
get
|
BobzhouCH/cyborg-acc
| 1 |
python
|
@classmethod
def get(cls, context, uuid):
db_dep = cls.dbapi.deployable_get(context, uuid)
obj_dep = cls._from_db_object(cls(context), db_dep)
return obj_dep
|
@classmethod
def get(cls, context, uuid):
db_dep = cls.dbapi.deployable_get(context, uuid)
obj_dep = cls._from_db_object(cls(context), db_dep)
return obj_dep<|docstring|>Find a DB Deployable and return an Obj Deployable.<|endoftext|>
|
d10ddfcf29c2d9cae57873d808e3672b77d6fa2883d6c9fa988b57d427864dc1
|
@classmethod
def get_by_host(cls, context, host):
'Get a Deployable by host.'
db_deps = cls.dbapi.deployable_get_by_host(context, host)
return cls._from_db_object_list(context, db_deps)
|
Get a Deployable by host.
|
cyborg/objects/deployable.py
|
get_by_host
|
BobzhouCH/cyborg-acc
| 1 |
python
|
@classmethod
def get_by_host(cls, context, host):
db_deps = cls.dbapi.deployable_get_by_host(context, host)
return cls._from_db_object_list(context, db_deps)
|
@classmethod
def get_by_host(cls, context, host):
db_deps = cls.dbapi.deployable_get_by_host(context, host)
return cls._from_db_object_list(context, db_deps)<|docstring|>Get a Deployable by host.<|endoftext|>
|
bdba23228ad6837e4c7133fc0e35ec498388a7e6d98fb47a295fd876c0eb05af
|
@classmethod
def list(cls, context):
'Return a list of Deployable objects.'
db_deps = cls.dbapi.deployable_list(context)
return cls._from_db_object_list(context, db_deps)
|
Return a list of Deployable objects.
|
cyborg/objects/deployable.py
|
list
|
BobzhouCH/cyborg-acc
| 1 |
python
|
@classmethod
def list(cls, context):
db_deps = cls.dbapi.deployable_list(context)
return cls._from_db_object_list(context, db_deps)
|
@classmethod
def list(cls, context):
db_deps = cls.dbapi.deployable_list(context)
return cls._from_db_object_list(context, db_deps)<|docstring|>Return a list of Deployable objects.<|endoftext|>
|
74eb166a14a2a5cf7d6ac6ca5a7a88771ef2c0f09e3740a46673492f7cba4341
|
def save(self, context):
'Update a Deployable record in the DB.'
updates = self.obj_get_changes()
db_dep = self.dbapi.deployable_update(context, self.uuid, updates)
self._from_db_object(self, db_dep)
|
Update a Deployable record in the DB.
|
cyborg/objects/deployable.py
|
save
|
BobzhouCH/cyborg-acc
| 1 |
python
|
def save(self, context):
updates = self.obj_get_changes()
db_dep = self.dbapi.deployable_update(context, self.uuid, updates)
self._from_db_object(self, db_dep)
|
def save(self, context):
updates = self.obj_get_changes()
db_dep = self.dbapi.deployable_update(context, self.uuid, updates)
self._from_db_object(self, db_dep)<|docstring|>Update a Deployable record in the DB.<|endoftext|>
|
ebe7120816eb7306840e9b21655c9accd655b959e3382a47a7283173cfcda1b9
|
def destroy(self, context):
'Delete a Deployable from the DB.'
self.dbapi.deployable_delete(context, self.uuid)
self.obj_reset_changes()
|
Delete a Deployable from the DB.
|
cyborg/objects/deployable.py
|
destroy
|
BobzhouCH/cyborg-acc
| 1 |
python
|
def destroy(self, context):
self.dbapi.deployable_delete(context, self.uuid)
self.obj_reset_changes()
|
def destroy(self, context):
self.dbapi.deployable_delete(context, self.uuid)
self.obj_reset_changes()<|docstring|>Delete a Deployable from the DB.<|endoftext|>
|
867fca05377d97a5076a6872667f2103c03da73c94bd247936f3c3a40d40321e
|
def add_attribute(self, attribute):
'add a attribute object to the attribute_list.\n If the attribute already exists, it will update the value,\n otherwise, the vf will be appended to the list.\n '
if (not isinstance(attribute, Attribute)):
raise exception.InvalidDeployType()
for exist_attr in self.attributes_list:
if base.obj_equal_prims(vf, exist_attr):
LOG.warning('The attribute already exists.')
return None
|
add a attribute object to the attribute_list.
If the attribute already exists, it will update the value,
otherwise, the vf will be appended to the list.
|
cyborg/objects/deployable.py
|
add_attribute
|
BobzhouCH/cyborg-acc
| 1 |
python
|
def add_attribute(self, attribute):
'add a attribute object to the attribute_list.\n If the attribute already exists, it will update the value,\n otherwise, the vf will be appended to the list.\n '
if (not isinstance(attribute, Attribute)):
raise exception.InvalidDeployType()
for exist_attr in self.attributes_list:
if base.obj_equal_prims(vf, exist_attr):
LOG.warning('The attribute already exists.')
return None
|
def add_attribute(self, attribute):
'add a attribute object to the attribute_list.\n If the attribute already exists, it will update the value,\n otherwise, the vf will be appended to the list.\n '
if (not isinstance(attribute, Attribute)):
raise exception.InvalidDeployType()
for exist_attr in self.attributes_list:
if base.obj_equal_prims(vf, exist_attr):
LOG.warning('The attribute already exists.')
return None<|docstring|>add a attribute object to the attribute_list.
If the attribute already exists, it will update the value,
otherwise, the vf will be appended to the list.<|endoftext|>
|
dcce62704d560d0fa2b3df00a0f09a007f4ef703dd4b7caee85fdad75baf8a4e
|
def __init__(self, period=None, **kwargs):
'Constructor for Trigonometric function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n '
CenteredBasisFn.__init__(self, **kwargs)
try:
self.period = float(period)
except:
raise TypeError('Period {0} cannot be interpreted as float'.format(period))
if (self.period == 0):
raise ValueError('Time period for a trigonometric function cannot be zero.')
self.fnpointer = None
self.radfactor = (2 * np.pi)
|
Constructor for Trigonometric function.
Parameters
----------
tmin: str (or) datetime.datetime
Left edge of active period (keyword)
tmax: str (or) datetime.datetime
Right edge of active period (keyword)
tref: str (or) datetime.datetime
Reference epoch (time zero) (keyword)
units: str
Units to interpret tau (keyword)
period: str (or) float
Time period for the trigonometric function
side: str
Alternate interface to tmin, tmax
|
src/timefn/Trigonometry.py
|
__init__
|
mgovorcin/fringe
| 52 |
python
|
def __init__(self, period=None, **kwargs):
'Constructor for Trigonometric function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n '
CenteredBasisFn.__init__(self, **kwargs)
try:
self.period = float(period)
except:
raise TypeError('Period {0} cannot be interpreted as float'.format(period))
if (self.period == 0):
raise ValueError('Time period for a trigonometric function cannot be zero.')
self.fnpointer = None
self.radfactor = (2 * np.pi)
|
def __init__(self, period=None, **kwargs):
'Constructor for Trigonometric function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n '
CenteredBasisFn.__init__(self, **kwargs)
try:
self.period = float(period)
except:
raise TypeError('Period {0} cannot be interpreted as float'.format(period))
if (self.period == 0):
raise ValueError('Time period for a trigonometric function cannot be zero.')
self.fnpointer = None
self.radfactor = (2 * np.pi)<|docstring|>Constructor for Trigonometric function.
Parameters
----------
tmin: str (or) datetime.datetime
Left edge of active period (keyword)
tmax: str (or) datetime.datetime
Right edge of active period (keyword)
tref: str (or) datetime.datetime
Reference epoch (time zero) (keyword)
units: str
Units to interpret tau (keyword)
period: str (or) float
Time period for the trigonometric function
side: str
Alternate interface to tmin, tmax<|endoftext|>
|
57d0b8b2cf730d774779718d5963c11f0533374275d6338efee99d34869c8b21
|
def computeRaw(self, tinput):
'Evaluation of the trigonometric function.\n '
return self.fnpointer(((self.radfactor * self.normalizedTime(tinput)) / self.period))
|
Evaluation of the trigonometric function.
|
src/timefn/Trigonometry.py
|
computeRaw
|
mgovorcin/fringe
| 52 |
python
|
def computeRaw(self, tinput):
'\n '
return self.fnpointer(((self.radfactor * self.normalizedTime(tinput)) / self.period))
|
def computeRaw(self, tinput):
'\n '
return self.fnpointer(((self.radfactor * self.normalizedTime(tinput)) / self.period))<|docstring|>Evaluation of the trigonometric function.<|endoftext|>
|
5f1ee71b6d1de198175bf80233f7649d91cb4c5f52c5aee7a5cc8ca91c511331
|
def kwrepr(self):
'Keyword representation.\n '
outstr = CenteredBasisFn.kwrepr(self)
if outstr:
outstr += ','
return ((outstr + 'period=') + str(self.period))
|
Keyword representation.
|
src/timefn/Trigonometry.py
|
kwrepr
|
mgovorcin/fringe
| 52 |
python
|
def kwrepr(self):
'\n '
outstr = CenteredBasisFn.kwrepr(self)
if outstr:
outstr += ','
return ((outstr + 'period=') + str(self.period))
|
def kwrepr(self):
'\n '
outstr = CenteredBasisFn.kwrepr(self)
if outstr:
outstr += ','
return ((outstr + 'period=') + str(self.period))<|docstring|>Keyword representation.<|endoftext|>
|
18806746712ba23b152ccff05d2f4343e6448622b31666b3f2517fee93e90da3
|
def __init__(self, **kwargs):
'Constructor for Cosine function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n '
Trigonometry.__init__(self, **kwargs)
self.fnpointer = np.cos
|
Constructor for Cosine function.
Parameters
----------
tmin: str (or) datetime.datetime
Left edge of active period (keyword)
tmax: str (or) datetime.datetime
Right edge of active period (keyword)
tref: str (or) datetime.datetime
Reference epoch (time zero) (keyword)
units: str
Units to interpret tau (keyword)
period: str (or) float
Time period for the trigonometric function
side: str
Alternate interface to tmin, tmax
|
src/timefn/Trigonometry.py
|
__init__
|
mgovorcin/fringe
| 52 |
python
|
def __init__(self, **kwargs):
'Constructor for Cosine function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n '
Trigonometry.__init__(self, **kwargs)
self.fnpointer = np.cos
|
def __init__(self, **kwargs):
'Constructor for Cosine function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n '
Trigonometry.__init__(self, **kwargs)
self.fnpointer = np.cos<|docstring|>Constructor for Cosine function.
Parameters
----------
tmin: str (or) datetime.datetime
Left edge of active period (keyword)
tmax: str (or) datetime.datetime
Right edge of active period (keyword)
tref: str (or) datetime.datetime
Reference epoch (time zero) (keyword)
units: str
Units to interpret tau (keyword)
period: str (or) float
Time period for the trigonometric function
side: str
Alternate interface to tmin, tmax<|endoftext|>
|
cfe99a107f5298d51be423e4dcf49bc86a667343857ed0ea31d0897ca13e8b2e
|
def __init__(self, **kwargs):
'Constructor for Sine function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n \n '
Trigonometry.__init__(self, **kwargs)
self.fnpointer = np.sin
|
Constructor for Sine function.
Parameters
----------
tmin: str (or) datetime.datetime
Left edge of active period (keyword)
tmax: str (or) datetime.datetime
Right edge of active period (keyword)
tref: str (or) datetime.datetime
Reference epoch (time zero) (keyword)
units: str
Units to interpret tau (keyword)
period: str (or) float
Time period for the trigonometric function
side: str
Alternate interface to tmin, tmax
|
src/timefn/Trigonometry.py
|
__init__
|
mgovorcin/fringe
| 52 |
python
|
def __init__(self, **kwargs):
'Constructor for Sine function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n \n '
Trigonometry.__init__(self, **kwargs)
self.fnpointer = np.sin
|
def __init__(self, **kwargs):
'Constructor for Sine function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n \n '
Trigonometry.__init__(self, **kwargs)
self.fnpointer = np.sin<|docstring|>Constructor for Sine function.
Parameters
----------
tmin: str (or) datetime.datetime
Left edge of active period (keyword)
tmax: str (or) datetime.datetime
Right edge of active period (keyword)
tref: str (or) datetime.datetime
Reference epoch (time zero) (keyword)
units: str
Units to interpret tau (keyword)
period: str (or) float
Time period for the trigonometric function
side: str
Alternate interface to tmin, tmax<|endoftext|>
|
4a03901017dede28afebbfa0bdb09473ef83df6b3da6cf5e210094909f24ac2a
|
def __init__(self, **kwargs):
'Constructor for arctan function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n \n '
Trigonometry.__init__(self, **kwargs)
self.fnpointer = np.arctan
self.radfactor = 1.0
|
Constructor for arctan function.
Parameters
----------
tmin: str (or) datetime.datetime
Left edge of active period (keyword)
tmax: str (or) datetime.datetime
Right edge of active period (keyword)
tref: str (or) datetime.datetime
Reference epoch (time zero) (keyword)
units: str
Units to interpret tau (keyword)
period: str (or) float
Time period for the trigonometric function
side: str
Alternate interface to tmin, tmax
|
src/timefn/Trigonometry.py
|
__init__
|
mgovorcin/fringe
| 52 |
python
|
def __init__(self, **kwargs):
'Constructor for arctan function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n \n '
Trigonometry.__init__(self, **kwargs)
self.fnpointer = np.arctan
self.radfactor = 1.0
|
def __init__(self, **kwargs):
'Constructor for arctan function.\n\n Parameters\n ----------\n tmin: str (or) datetime.datetime\n Left edge of active period (keyword)\n tmax: str (or) datetime.datetime\n Right edge of active period (keyword)\n tref: str (or) datetime.datetime\n Reference epoch (time zero) (keyword)\n units: str\n Units to interpret tau (keyword)\n period: str (or) float\n Time period for the trigonometric function\n side: str\n Alternate interface to tmin, tmax\n \n '
Trigonometry.__init__(self, **kwargs)
self.fnpointer = np.arctan
self.radfactor = 1.0<|docstring|>Constructor for arctan function.
Parameters
----------
tmin: str (or) datetime.datetime
Left edge of active period (keyword)
tmax: str (or) datetime.datetime
Right edge of active period (keyword)
tref: str (or) datetime.datetime
Reference epoch (time zero) (keyword)
units: str
Units to interpret tau (keyword)
period: str (or) float
Time period for the trigonometric function
side: str
Alternate interface to tmin, tmax<|endoftext|>
|
77952ad5ddcbb55e0e8c82902c9fd3b85ef0f05919bc196d151a0e5624b79a92
|
def create_person(self, first_name, last_name):
'\n\n :param first_name: This is the param that is for the first name of the person\n :param last_name: this is the last name of the person\n :return: it returns true so you know what happened, else check logs\n '
try:
(self.user, created) = Person.get_or_create(first_name=first_name, last_name=last_name)
if self.user:
logging.info('Data Inserted')
return True
except Exception as ex:
logging.error(('Error in Data Creation' + str(ex)))
return False
|
:param first_name: This is the param that is for the first name of the person
:param last_name: this is the last name of the person
:return: it returns true so you know what happened, else check logs
|
GAddress/Person.py
|
create_person
|
aki263/Ginger
| 0 |
python
|
def create_person(self, first_name, last_name):
'\n\n :param first_name: This is the param that is for the first name of the person\n :param last_name: this is the last name of the person\n :return: it returns true so you know what happened, else check logs\n '
try:
(self.user, created) = Person.get_or_create(first_name=first_name, last_name=last_name)
if self.user:
logging.info('Data Inserted')
return True
except Exception as ex:
logging.error(('Error in Data Creation' + str(ex)))
return False
|
def create_person(self, first_name, last_name):
'\n\n :param first_name: This is the param that is for the first name of the person\n :param last_name: this is the last name of the person\n :return: it returns true so you know what happened, else check logs\n '
try:
(self.user, created) = Person.get_or_create(first_name=first_name, last_name=last_name)
if self.user:
logging.info('Data Inserted')
return True
except Exception as ex:
logging.error(('Error in Data Creation' + str(ex)))
return False<|docstring|>:param first_name: This is the param that is for the first name of the person
:param last_name: this is the last name of the person
:return: it returns true so you know what happened, else check logs<|endoftext|>
|
37466248be341a0fe66ff355d07976ca909f02f24769331d708cd2b440f20877
|
def add_phone_for_user(self, phone_list=list()):
'\n\n :param phone_list: this takes in list of phone number and links it to person\n :return True\n '
try:
for phone in phone_list:
if ((len(phone) != 10) and (phone is not None)):
if PhoneNumber.create(PersonModel=self.user, phone=phone):
logging.info('Phone number Inserted for User')
return True
else:
logging.error('Phone number must be of 10 digits')
except Exception as ex:
logging.error('Error in phone number insertion')
return False
|
:param phone_list: this takes in list of phone number and links it to person
:return True
|
GAddress/Person.py
|
add_phone_for_user
|
aki263/Ginger
| 0 |
python
|
def add_phone_for_user(self, phone_list=list()):
'\n\n :param phone_list: this takes in list of phone number and links it to person\n :return True\n '
try:
for phone in phone_list:
if ((len(phone) != 10) and (phone is not None)):
if PhoneNumber.create(PersonModel=self.user, phone=phone):
logging.info('Phone number Inserted for User')
return True
else:
logging.error('Phone number must be of 10 digits')
except Exception as ex:
logging.error('Error in phone number insertion')
return False
|
def add_phone_for_user(self, phone_list=list()):
'\n\n :param phone_list: this takes in list of phone number and links it to person\n :return True\n '
try:
for phone in phone_list:
if ((len(phone) != 10) and (phone is not None)):
if PhoneNumber.create(PersonModel=self.user, phone=phone):
logging.info('Phone number Inserted for User')
return True
else:
logging.error('Phone number must be of 10 digits')
except Exception as ex:
logging.error('Error in phone number insertion')
return False<|docstring|>:param phone_list: this takes in list of phone number and links it to person
:return True<|endoftext|>
|
c9b57d022c6314d520cbe7cc772f64084000a13c62597057625bbb6048e9a4dd
|
def add_user_to_group(self, group_name):
'\n This links the person to a given group, if group doesnt exits, it creates the group\n :param group_name: name of the group\n :return: true or false\n '
try:
(grp, created) = Group.get_or_create(group_name=group_name)
if PersonGroup.create(PersonModel=self.user, GroupModel=grp):
return True
except Exception as ex:
logging.error(('Error in user insertion in Group ' + str(ex)))
return False
|
This links the person to a given group, if group doesnt exits, it creates the group
:param group_name: name of the group
:return: true or false
|
GAddress/Person.py
|
add_user_to_group
|
aki263/Ginger
| 0 |
python
|
def add_user_to_group(self, group_name):
'\n This links the person to a given group, if group doesnt exits, it creates the group\n :param group_name: name of the group\n :return: true or false\n '
try:
(grp, created) = Group.get_or_create(group_name=group_name)
if PersonGroup.create(PersonModel=self.user, GroupModel=grp):
return True
except Exception as ex:
logging.error(('Error in user insertion in Group ' + str(ex)))
return False
|
def add_user_to_group(self, group_name):
'\n This links the person to a given group, if group doesnt exits, it creates the group\n :param group_name: name of the group\n :return: true or false\n '
try:
(grp, created) = Group.get_or_create(group_name=group_name)
if PersonGroup.create(PersonModel=self.user, GroupModel=grp):
return True
except Exception as ex:
logging.error(('Error in user insertion in Group ' + str(ex)))
return False<|docstring|>This links the person to a given group, if group doesnt exits, it creates the group
:param group_name: name of the group
:return: true or false<|endoftext|>
|
ea674aef053508881a64565c1b31ff4d1c4fbaf80aa97287bed79908fa52cbb6
|
def add_address_for_user(self, address):
'\n This addes the address to the user\n :param address: address as string\n :return: true or false\n '
try:
if ((address is not None) or (address is not '')):
if Address.get_or_create(PersonModel=self.user, address=address):
logging.info('Addess added for person')
return True
else:
logging.error('Address is empty or none')
except Exception as ex:
logging.error(('Address creation error ' + str(ex)))
return False
|
This addes the address to the user
:param address: address as string
:return: true or false
|
GAddress/Person.py
|
add_address_for_user
|
aki263/Ginger
| 0 |
python
|
def add_address_for_user(self, address):
'\n This addes the address to the user\n :param address: address as string\n :return: true or false\n '
try:
if ((address is not None) or (address is not )):
if Address.get_or_create(PersonModel=self.user, address=address):
logging.info('Addess added for person')
return True
else:
logging.error('Address is empty or none')
except Exception as ex:
logging.error(('Address creation error ' + str(ex)))
return False
|
def add_address_for_user(self, address):
'\n This addes the address to the user\n :param address: address as string\n :return: true or false\n '
try:
if ((address is not None) or (address is not )):
if Address.get_or_create(PersonModel=self.user, address=address):
logging.info('Addess added for person')
return True
else:
logging.error('Address is empty or none')
except Exception as ex:
logging.error(('Address creation error ' + str(ex)))
return False<|docstring|>This addes the address to the user
:param address: address as string
:return: true or false<|endoftext|>
|
7e816106e2069d4617134513226f71100f442d88fc8e3d6be0a7f3626f14daf8
|
def add_email_for_user(self, email):
'\n Links email with the user\n :param email: takes in the email\n :return: true or false\n '
try:
if ((email is not None) or (email is not '')):
if Email.get_or_create(PersonModel=self.user, email=email):
logging.info('Email added for person')
return True
else:
logging.error('Email is empty or none')
except Exception as ex:
logging.error(('Email creation error ' + str(ex)))
return False
|
Links email with the user
:param email: takes in the email
:return: true or false
|
GAddress/Person.py
|
add_email_for_user
|
aki263/Ginger
| 0 |
python
|
def add_email_for_user(self, email):
'\n Links email with the user\n :param email: takes in the email\n :return: true or false\n '
try:
if ((email is not None) or (email is not )):
if Email.get_or_create(PersonModel=self.user, email=email):
logging.info('Email added for person')
return True
else:
logging.error('Email is empty or none')
except Exception as ex:
logging.error(('Email creation error ' + str(ex)))
return False
|
def add_email_for_user(self, email):
'\n Links email with the user\n :param email: takes in the email\n :return: true or false\n '
try:
if ((email is not None) or (email is not )):
if Email.get_or_create(PersonModel=self.user, email=email):
logging.info('Email added for person')
return True
else:
logging.error('Email is empty or none')
except Exception as ex:
logging.error(('Email creation error ' + str(ex)))
return False<|docstring|>Links email with the user
:param email: takes in the email
:return: true or false<|endoftext|>
|
8745349d0ef3de4540cae87383a66ec0439f9f92d9fe9463ebeb5a2b39a552bf
|
def get_person_groups(self):
"\n THis get all the group of a given person\n :return list of group with the total in touple like (6, ['111111', '111111', '111111', '111111', '111111', '111111'])\n "
try:
temp = [usr.group_name for usr in self.user.find_user_group()]
return (len(temp), temp)
except Exception as ex:
logging.error(('Error in getting person groups ' + str(ex)))
|
THis get all the group of a given person
:return list of group with the total in touple like (6, ['111111', '111111', '111111', '111111', '111111', '111111'])
|
GAddress/Person.py
|
get_person_groups
|
aki263/Ginger
| 0 |
python
|
def get_person_groups(self):
"\n THis get all the group of a given person\n :return list of group with the total in touple like (6, ['111111', '111111', '111111', '111111', '111111', '111111'])\n "
try:
temp = [usr.group_name for usr in self.user.find_user_group()]
return (len(temp), temp)
except Exception as ex:
logging.error(('Error in getting person groups ' + str(ex)))
|
def get_person_groups(self):
"\n THis get all the group of a given person\n :return list of group with the total in touple like (6, ['111111', '111111', '111111', '111111', '111111', '111111'])\n "
try:
temp = [usr.group_name for usr in self.user.find_user_group()]
return (len(temp), temp)
except Exception as ex:
logging.error(('Error in getting person groups ' + str(ex)))<|docstring|>THis get all the group of a given person
:return list of group with the total in touple like (6, ['111111', '111111', '111111', '111111', '111111', '111111'])<|endoftext|>
|
3a28e3afbe35f2da7587940f5d35bd92b6bdbf75a8edb80050e726d6fc186585
|
def get_person_emails(self):
"\n this return all the user email\n :return: (6, ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'])\n "
try:
temp = [emaill.email for emaill in self.user.find_user_email()]
return (len(temp), temp)
except Exception as ex:
logging.error(('Error in getting person emails ' + str(ex)))
|
this return all the user email
:return: (6, ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'])
|
GAddress/Person.py
|
get_person_emails
|
aki263/Ginger
| 0 |
python
|
def get_person_emails(self):
"\n this return all the user email\n :return: (6, ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'])\n "
try:
temp = [emaill.email for emaill in self.user.find_user_email()]
return (len(temp), temp)
except Exception as ex:
logging.error(('Error in getting person emails ' + str(ex)))
|
def get_person_emails(self):
"\n this return all the user email\n :return: (6, ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'])\n "
try:
temp = [emaill.email for emaill in self.user.find_user_email()]
return (len(temp), temp)
except Exception as ex:
logging.error(('Error in getting person emails ' + str(ex)))<|docstring|>this return all the user email
:return: (6, ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'])<|endoftext|>
|
6f2c2a1122004a2c7779a2f69140f33d582ac13fe6ef61ae0f852404b1b55e3a
|
def get_person_phonenumbers(self):
"\n this returns all the phone number of the user\n :return: (6, ['111111', '111111', '111111', '111111', '111111', '111111'])\n "
try:
temp = [emaill.phone for emaill in self.user.find_user_phone()]
return (len(temp), temp)
except Exception as ex:
logging.error(('Error in getting person phone numbers ' + str(ex)))
|
this returns all the phone number of the user
:return: (6, ['111111', '111111', '111111', '111111', '111111', '111111'])
|
GAddress/Person.py
|
get_person_phonenumbers
|
aki263/Ginger
| 0 |
python
|
def get_person_phonenumbers(self):
"\n this returns all the phone number of the user\n :return: (6, ['111111', '111111', '111111', '111111', '111111', '111111'])\n "
try:
temp = [emaill.phone for emaill in self.user.find_user_phone()]
return (len(temp), temp)
except Exception as ex:
logging.error(('Error in getting person phone numbers ' + str(ex)))
|
def get_person_phonenumbers(self):
"\n this returns all the phone number of the user\n :return: (6, ['111111', '111111', '111111', '111111', '111111', '111111'])\n "
try:
temp = [emaill.phone for emaill in self.user.find_user_phone()]
return (len(temp), temp)
except Exception as ex:
logging.error(('Error in getting person phone numbers ' + str(ex)))<|docstring|>this returns all the phone number of the user
:return: (6, ['111111', '111111', '111111', '111111', '111111', '111111'])<|endoftext|>
|
f925827b2cf1d9d97e27d1fe00b991352dd174408d0f53b5b2cbc046fc72c0fc
|
def find_person(self, name=None):
'\n This takes name and searches in db\n :param name: should have space to search in indivdually in fname and lname\n :return: list of names\n '
try:
if ((name != '') or (name != ' ')):
fname = lname = ''
if (' ' in name):
fname = name.split(' ')[0]
lname = name.split(' ')[1]
else:
fname = lname = name
return (x.first_name for x in self.user.select().where((Person.last_name.contains(lname) & Person.first_name.contains(fname))))
except Exception as ex:
logging.error(('Error in searching Person' + str(ex)))
|
This takes name and searches in db
:param name: should have space to search in indivdually in fname and lname
:return: list of names
|
GAddress/Person.py
|
find_person
|
aki263/Ginger
| 0 |
python
|
def find_person(self, name=None):
'\n This takes name and searches in db\n :param name: should have space to search in indivdually in fname and lname\n :return: list of names\n '
try:
if ((name != ) or (name != ' ')):
fname = lname =
if (' ' in name):
fname = name.split(' ')[0]
lname = name.split(' ')[1]
else:
fname = lname = name
return (x.first_name for x in self.user.select().where((Person.last_name.contains(lname) & Person.first_name.contains(fname))))
except Exception as ex:
logging.error(('Error in searching Person' + str(ex)))
|
def find_person(self, name=None):
'\n This takes name and searches in db\n :param name: should have space to search in indivdually in fname and lname\n :return: list of names\n '
try:
if ((name != ) or (name != ' ')):
fname = lname =
if (' ' in name):
fname = name.split(' ')[0]
lname = name.split(' ')[1]
else:
fname = lname = name
return (x.first_name for x in self.user.select().where((Person.last_name.contains(lname) & Person.first_name.contains(fname))))
except Exception as ex:
logging.error(('Error in searching Person' + str(ex)))<|docstring|>This takes name and searches in db
:param name: should have space to search in indivdually in fname and lname
:return: list of names<|endoftext|>
|
28460f3157c526d991f75611ee275fc21e296917fd84d169ed7b089a29b2ee05
|
def find_person_by_email(self, email=None):
'\n this will finf person with email\n :param email: you can supply either the exact string or a prefix string, ie. both "[email protected]" and "alex" should work\n :return: person\n '
try:
if ((email is not None) or (email is not '')):
temp = [emai.id for emai in Email.select().where(((Email.email == email) | Email.email.startswith(email)))]
return (len(temp), [x.first_name for x in Person.select().where((Person.id << temp))])
except Exception as ex:
logging.error('Error in fiding by email')
|
this will finf person with email
:param email: you can supply either the exact string or a prefix string, ie. both "[email protected]" and "alex" should work
:return: person
|
GAddress/Person.py
|
find_person_by_email
|
aki263/Ginger
| 0 |
python
|
def find_person_by_email(self, email=None):
'\n this will finf person with email\n :param email: you can supply either the exact string or a prefix string, ie. both "[email protected]" and "alex" should work\n :return: person\n '
try:
if ((email is not None) or (email is not )):
temp = [emai.id for emai in Email.select().where(((Email.email == email) | Email.email.startswith(email)))]
return (len(temp), [x.first_name for x in Person.select().where((Person.id << temp))])
except Exception as ex:
logging.error('Error in fiding by email')
|
def find_person_by_email(self, email=None):
'\n this will finf person with email\n :param email: you can supply either the exact string or a prefix string, ie. both "[email protected]" and "alex" should work\n :return: person\n '
try:
if ((email is not None) or (email is not )):
temp = [emai.id for emai in Email.select().where(((Email.email == email) | Email.email.startswith(email)))]
return (len(temp), [x.first_name for x in Person.select().where((Person.id << temp))])
except Exception as ex:
logging.error('Error in fiding by email')<|docstring|>this will finf person with email
:param email: you can supply either the exact string or a prefix string, ie. both "[email protected]" and "alex" should work
:return: person<|endoftext|>
|
3bd8ca6e6e07f64e9f0e17e4d674813cc68d518dfc3405af828b4cc7145699fa
|
def find_person_by_email_design(self, email=None):
'\n this will seach email\n you can supply any substring, ie. "comp" should work assuming "[email protected]" is an email address in the address book\n :param email:\n :return: person\n '
try:
if ((email is not None) or (email is not '')):
temp = [emai.id for emai in Email.select().where(Email.email.contains(email))]
return (len(temp), [x.first_name for x in Person.select().where((Person.id << temp))])
except Exception as ex:
logging.error('Error in fiding by email')
|
this will seach email
you can supply any substring, ie. "comp" should work assuming "[email protected]" is an email address in the address book
:param email:
:return: person
|
GAddress/Person.py
|
find_person_by_email_design
|
aki263/Ginger
| 0 |
python
|
def find_person_by_email_design(self, email=None):
'\n this will seach email\n you can supply any substring, ie. "comp" should work assuming "[email protected]" is an email address in the address book\n :param email:\n :return: person\n '
try:
if ((email is not None) or (email is not )):
temp = [emai.id for emai in Email.select().where(Email.email.contains(email))]
return (len(temp), [x.first_name for x in Person.select().where((Person.id << temp))])
except Exception as ex:
logging.error('Error in fiding by email')
|
def find_person_by_email_design(self, email=None):
'\n this will seach email\n you can supply any substring, ie. "comp" should work assuming "[email protected]" is an email address in the address book\n :param email:\n :return: person\n '
try:
if ((email is not None) or (email is not )):
temp = [emai.id for emai in Email.select().where(Email.email.contains(email))]
return (len(temp), [x.first_name for x in Person.select().where((Person.id << temp))])
except Exception as ex:
logging.error('Error in fiding by email')<|docstring|>this will seach email
you can supply any substring, ie. "comp" should work assuming "[email protected]" is an email address in the address book
:param email:
:return: person<|endoftext|>
|
63195d4b28ab4dac709aff56d6767e4df726203ab4c6fa7b71d8acbc9bd16cd2
|
@property
def enabled(self):
'Allows access via repo.enabled'
return (self._data.conf.enabled == 1)
|
Allows access via repo.enabled
|
doozerlib/repos.py
|
enabled
|
Ximinhan/doozer
| 16 |
python
|
@property
def enabled(self):
return (self._data.conf.enabled == 1)
|
@property
def enabled(self):
return (self._data.conf.enabled == 1)<|docstring|>Allows access via repo.enabled<|endoftext|>
|
91b113b29c94cbe51c9e4f57420dac8c988aa508e674abe87ffc443f9e627906
|
@enabled.setter
def enabled(self, val):
'Set enabled option without digging direct into the underlying data'
self._data.conf.enabled = (1 if val else 0)
|
Set enabled option without digging direct into the underlying data
|
doozerlib/repos.py
|
enabled
|
Ximinhan/doozer
| 16 |
python
|
@enabled.setter
def enabled(self, val):
self._data.conf.enabled = (1 if val else 0)
|
@enabled.setter
def enabled(self, val):
self._data.conf.enabled = (1 if val else 0)<|docstring|>Set enabled option without digging direct into the underlying data<|endoftext|>
|
923bba5a519eee4cd965c0231a35c5f0ee2ff9e2a90301a895c8c732e84ba6c4
|
def __repr__(self):
'For debugging mainly, to display contents as a dict'
return str(self._data)
|
For debugging mainly, to display contents as a dict
|
doozerlib/repos.py
|
__repr__
|
Ximinhan/doozer
| 16 |
python
|
def __repr__(self):
return str(self._data)
|
def __repr__(self):
return str(self._data)<|docstring|>For debugging mainly, to display contents as a dict<|endoftext|>
|
07c774c7f6e9489c0fb4a5b8db002f2e7150923ada6f85b131007f6198d77b56
|
def content_set(self, arch):
'Return content set name for given arch with sane fallbacks and error handling.'
if (arch not in self._valid_arches):
raise ValueError('{} is not a valid arch!')
if (arch in self._invalid_cs_arches):
return None
if (self._data.content_set[arch] is Missing):
if (self._data.content_set['default'] is Missing):
raise ValueError('{} does not contain a content_set for {} and no default was provided.'.format(self.name, arch))
return self._data.content_set['default']
else:
return self._data.content_set[arch]
|
Return content set name for given arch with sane fallbacks and error handling.
|
doozerlib/repos.py
|
content_set
|
Ximinhan/doozer
| 16 |
python
|
def content_set(self, arch):
if (arch not in self._valid_arches):
raise ValueError('{} is not a valid arch!')
if (arch in self._invalid_cs_arches):
return None
if (self._data.content_set[arch] is Missing):
if (self._data.content_set['default'] is Missing):
raise ValueError('{} does not contain a content_set for {} and no default was provided.'.format(self.name, arch))
return self._data.content_set['default']
else:
return self._data.content_set[arch]
|
def content_set(self, arch):
if (arch not in self._valid_arches):
raise ValueError('{} is not a valid arch!')
if (arch in self._invalid_cs_arches):
return None
if (self._data.content_set[arch] is Missing):
if (self._data.content_set['default'] is Missing):
raise ValueError('{} does not contain a content_set for {} and no default was provided.'.format(self.name, arch))
return self._data.content_set['default']
else:
return self._data.content_set[arch]<|docstring|>Return content set name for given arch with sane fallbacks and error handling.<|endoftext|>
|
d842f562bf07e28bccb6fc24e57f468cf8b9de8b3c3b84827cc7886b310cacc3
|
def conf_section(self, repotype, arch=ARCH_X86_64, enabled=None, section_name=None):
"\n Returns a str that represents a yum repo configuration section corresponding\n to this repo in group.yml.\n\n :param repotype: Whether to use signed or unsigned repos from group.yml\n :param arch: The architecture this section if being generated for (e.g. ppc64le or x86_64).\n :param enabled: If True|False, explicitly set 'enabled = 1|0' in section. If None, inherit group.yml setting.\n :param section_name: The section name to use if not the repo name in group.yml.\n :return: Returns a string representing a repo section in a yum configuration file. e.g.\n [rhel-7-server-ansible-2.4-rpms]\n gpgcheck = 0\n enabled = 0\n baseurl = http://pulp.dist.pr.../x86_64/ansible/2.4/os/\n name = rhel-7-server-ansible-2.4-rpms\n "
if (not repotype):
repotype = 'unsigned'
if (arch not in self._valid_arches):
raise ValueError('{} does not identify a yum repository for arch: {}'.format(self.name, arch))
if (not section_name):
section_name = self.name
result = '[{}]\n'.format(section_name)
for k in sorted(self._data.conf.keys()):
v = self._data.conf[k]
if (k == 'ci_alignment'):
continue
line = '{} = {}\n'
if (k == 'baseurl'):
line = line.format(k, self.baseurl(repotype, arch))
elif (k == 'name'):
line = line.format(k, section_name)
elif (k == 'extra_options'):
opt_lines = ''
for (opt, val) in v.items():
opt_lines += '{} = {}\n'.format(opt, val)
line = opt_lines
else:
if ((k == 'enabled') and (enabled is not None)):
v = (1 if enabled else 0)
line = line.format(k, v)
result += line
if (self._data.conf.get('gpgcheck', None) is None):
if ((repotype == 'signed') and self.gpgcheck):
result += 'gpgcheck = 1\n'
else:
result += 'gpgcheck = 0\n'
if (self._data.conf.get('gpgkey', None) is None):
result += 'gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release\n'
result += '\n'
return result
|
Returns a str that represents a yum repo configuration section corresponding
to this repo in group.yml.
:param repotype: Whether to use signed or unsigned repos from group.yml
:param arch: The architecture this section if being generated for (e.g. ppc64le or x86_64).
:param enabled: If True|False, explicitly set 'enabled = 1|0' in section. If None, inherit group.yml setting.
:param section_name: The section name to use if not the repo name in group.yml.
:return: Returns a string representing a repo section in a yum configuration file. e.g.
[rhel-7-server-ansible-2.4-rpms]
gpgcheck = 0
enabled = 0
baseurl = http://pulp.dist.pr.../x86_64/ansible/2.4/os/
name = rhel-7-server-ansible-2.4-rpms
|
doozerlib/repos.py
|
conf_section
|
Ximinhan/doozer
| 16 |
python
|
def conf_section(self, repotype, arch=ARCH_X86_64, enabled=None, section_name=None):
"\n Returns a str that represents a yum repo configuration section corresponding\n to this repo in group.yml.\n\n :param repotype: Whether to use signed or unsigned repos from group.yml\n :param arch: The architecture this section if being generated for (e.g. ppc64le or x86_64).\n :param enabled: If True|False, explicitly set 'enabled = 1|0' in section. If None, inherit group.yml setting.\n :param section_name: The section name to use if not the repo name in group.yml.\n :return: Returns a string representing a repo section in a yum configuration file. e.g.\n [rhel-7-server-ansible-2.4-rpms]\n gpgcheck = 0\n enabled = 0\n baseurl = http://pulp.dist.pr.../x86_64/ansible/2.4/os/\n name = rhel-7-server-ansible-2.4-rpms\n "
if (not repotype):
repotype = 'unsigned'
if (arch not in self._valid_arches):
raise ValueError('{} does not identify a yum repository for arch: {}'.format(self.name, arch))
if (not section_name):
section_name = self.name
result = '[{}]\n'.format(section_name)
for k in sorted(self._data.conf.keys()):
v = self._data.conf[k]
if (k == 'ci_alignment'):
continue
line = '{} = {}\n'
if (k == 'baseurl'):
line = line.format(k, self.baseurl(repotype, arch))
elif (k == 'name'):
line = line.format(k, section_name)
elif (k == 'extra_options'):
opt_lines =
for (opt, val) in v.items():
opt_lines += '{} = {}\n'.format(opt, val)
line = opt_lines
else:
if ((k == 'enabled') and (enabled is not None)):
v = (1 if enabled else 0)
line = line.format(k, v)
result += line
if (self._data.conf.get('gpgcheck', None) is None):
if ((repotype == 'signed') and self.gpgcheck):
result += 'gpgcheck = 1\n'
else:
result += 'gpgcheck = 0\n'
if (self._data.conf.get('gpgkey', None) is None):
result += 'gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release\n'
result += '\n'
return result
|
def conf_section(self, repotype, arch=ARCH_X86_64, enabled=None, section_name=None):
"\n Returns a str that represents a yum repo configuration section corresponding\n to this repo in group.yml.\n\n :param repotype: Whether to use signed or unsigned repos from group.yml\n :param arch: The architecture this section if being generated for (e.g. ppc64le or x86_64).\n :param enabled: If True|False, explicitly set 'enabled = 1|0' in section. If None, inherit group.yml setting.\n :param section_name: The section name to use if not the repo name in group.yml.\n :return: Returns a string representing a repo section in a yum configuration file. e.g.\n [rhel-7-server-ansible-2.4-rpms]\n gpgcheck = 0\n enabled = 0\n baseurl = http://pulp.dist.pr.../x86_64/ansible/2.4/os/\n name = rhel-7-server-ansible-2.4-rpms\n "
if (not repotype):
repotype = 'unsigned'
if (arch not in self._valid_arches):
raise ValueError('{} does not identify a yum repository for arch: {}'.format(self.name, arch))
if (not section_name):
section_name = self.name
result = '[{}]\n'.format(section_name)
for k in sorted(self._data.conf.keys()):
v = self._data.conf[k]
if (k == 'ci_alignment'):
continue
line = '{} = {}\n'
if (k == 'baseurl'):
line = line.format(k, self.baseurl(repotype, arch))
elif (k == 'name'):
line = line.format(k, section_name)
elif (k == 'extra_options'):
opt_lines =
for (opt, val) in v.items():
opt_lines += '{} = {}\n'.format(opt, val)
line = opt_lines
else:
if ((k == 'enabled') and (enabled is not None)):
v = (1 if enabled else 0)
line = line.format(k, v)
result += line
if (self._data.conf.get('gpgcheck', None) is None):
if ((repotype == 'signed') and self.gpgcheck):
result += 'gpgcheck = 1\n'
else:
result += 'gpgcheck = 0\n'
if (self._data.conf.get('gpgkey', None) is None):
result += 'gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release\n'
result += '\n'
return result<|docstring|>Returns a str that represents a yum repo configuration section corresponding
to this repo in group.yml.
:param repotype: Whether to use signed or unsigned repos from group.yml
:param arch: The architecture this section if being generated for (e.g. ppc64le or x86_64).
:param enabled: If True|False, explicitly set 'enabled = 1|0' in section. If None, inherit group.yml setting.
:param section_name: The section name to use if not the repo name in group.yml.
:return: Returns a string representing a repo section in a yum configuration file. e.g.
[rhel-7-server-ansible-2.4-rpms]
gpgcheck = 0
enabled = 0
baseurl = http://pulp.dist.pr.../x86_64/ansible/2.4/os/
name = rhel-7-server-ansible-2.4-rpms<|endoftext|>
|
0b466a34d8b24b459d46a6eae6cf52740cb4d9ac9401cbce91f159e9b48b7f20
|
def __getitem__(self, item):
'Allows getting a Repo() object simply by name via repos[repo_name]'
if (item not in self._repos):
raise ValueError('{} is not a valid repo name!'.format(item))
return self._repos[item]
|
Allows getting a Repo() object simply by name via repos[repo_name]
|
doozerlib/repos.py
|
__getitem__
|
Ximinhan/doozer
| 16 |
python
|
def __getitem__(self, item):
if (item not in self._repos):
raise ValueError('{} is not a valid repo name!'.format(item))
return self._repos[item]
|
def __getitem__(self, item):
if (item not in self._repos):
raise ValueError('{} is not a valid repo name!'.format(item))
return self._repos[item]<|docstring|>Allows getting a Repo() object simply by name via repos[repo_name]<|endoftext|>
|
8a14f5dfc8d596cfd4d7c95daa2fc77c2b82d78077efb17fd47c8e2779617fbb
|
def __repr__(self):
'Mainly for debugging to dump a dict representation of the collection'
return str(self._repos)
|
Mainly for debugging to dump a dict representation of the collection
|
doozerlib/repos.py
|
__repr__
|
Ximinhan/doozer
| 16 |
python
|
def __repr__(self):
return str(self._repos)
|
def __repr__(self):
return str(self._repos)<|docstring|>Mainly for debugging to dump a dict representation of the collection<|endoftext|>
|
641080a37c4e87de8dde90f3854b4f280ce321e8cb1425dca703ce00648fb16d
|
def repo_file(self, repo_type, enabled_repos=[], empty_repos=[], arch=None):
'\n Returns a str defining a list of repo configuration secions for a yum configuration file.\n :param repo_type: Whether to prefer signed or unsigned repos.\n :param enabled_repos: A list of group.yml repo names which should be enabled. If a repo is enabled==1\n in group.yml, that setting takes precedence over this list. If not enabled==1 in group.yml and not\n found in this list, the repo will be returned as enabled==0.\n :param empty_repos: A list of repo names to return defined as no-op yum repos.\n :param arch: The architecture for which this repository should be generated. If None, all architectures\n will be included in the returned str.\n '
result = ''
for r in self._repos.values():
enabled = r.enabled
if (enabled_repos and (r.name in enabled_repos)):
enabled = True
if arch:
result += r.conf_section(repo_type, enabled=enabled, arch=arch, section_name=r.name)
else:
for iarch in r.arches:
section_name = '{}-{}'.format(r.name, iarch)
result += r.conf_section(repo_type, enabled=enabled, arch=iarch, section_name=section_name)
for er in empty_repos:
result += EMPTY_REPO.format(er)
return result
|
Returns a str defining a list of repo configuration secions for a yum configuration file.
:param repo_type: Whether to prefer signed or unsigned repos.
:param enabled_repos: A list of group.yml repo names which should be enabled. If a repo is enabled==1
in group.yml, that setting takes precedence over this list. If not enabled==1 in group.yml and not
found in this list, the repo will be returned as enabled==0.
:param empty_repos: A list of repo names to return defined as no-op yum repos.
:param arch: The architecture for which this repository should be generated. If None, all architectures
will be included in the returned str.
|
doozerlib/repos.py
|
repo_file
|
Ximinhan/doozer
| 16 |
python
|
def repo_file(self, repo_type, enabled_repos=[], empty_repos=[], arch=None):
'\n Returns a str defining a list of repo configuration secions for a yum configuration file.\n :param repo_type: Whether to prefer signed or unsigned repos.\n :param enabled_repos: A list of group.yml repo names which should be enabled. If a repo is enabled==1\n in group.yml, that setting takes precedence over this list. If not enabled==1 in group.yml and not\n found in this list, the repo will be returned as enabled==0.\n :param empty_repos: A list of repo names to return defined as no-op yum repos.\n :param arch: The architecture for which this repository should be generated. If None, all architectures\n will be included in the returned str.\n '
result =
for r in self._repos.values():
enabled = r.enabled
if (enabled_repos and (r.name in enabled_repos)):
enabled = True
if arch:
result += r.conf_section(repo_type, enabled=enabled, arch=arch, section_name=r.name)
else:
for iarch in r.arches:
section_name = '{}-{}'.format(r.name, iarch)
result += r.conf_section(repo_type, enabled=enabled, arch=iarch, section_name=section_name)
for er in empty_repos:
result += EMPTY_REPO.format(er)
return result
|
def repo_file(self, repo_type, enabled_repos=[], empty_repos=[], arch=None):
'\n Returns a str defining a list of repo configuration secions for a yum configuration file.\n :param repo_type: Whether to prefer signed or unsigned repos.\n :param enabled_repos: A list of group.yml repo names which should be enabled. If a repo is enabled==1\n in group.yml, that setting takes precedence over this list. If not enabled==1 in group.yml and not\n found in this list, the repo will be returned as enabled==0.\n :param empty_repos: A list of repo names to return defined as no-op yum repos.\n :param arch: The architecture for which this repository should be generated. If None, all architectures\n will be included in the returned str.\n '
result =
for r in self._repos.values():
enabled = r.enabled
if (enabled_repos and (r.name in enabled_repos)):
enabled = True
if arch:
result += r.conf_section(repo_type, enabled=enabled, arch=arch, section_name=r.name)
else:
for iarch in r.arches:
section_name = '{}-{}'.format(r.name, iarch)
result += r.conf_section(repo_type, enabled=enabled, arch=iarch, section_name=section_name)
for er in empty_repos:
result += EMPTY_REPO.format(er)
return result<|docstring|>Returns a str defining a list of repo configuration secions for a yum configuration file.
:param repo_type: Whether to prefer signed or unsigned repos.
:param enabled_repos: A list of group.yml repo names which should be enabled. If a repo is enabled==1
in group.yml, that setting takes precedence over this list. If not enabled==1 in group.yml and not
found in this list, the repo will be returned as enabled==0.
:param empty_repos: A list of repo names to return defined as no-op yum repos.
:param arch: The architecture for which this repository should be generated. If None, all architectures
will be included in the returned str.<|endoftext|>
|
74e743d9fca11a0839ed445f0030627b793862a1562c20633d6d60093dccf18e
|
def content_sets(self, enabled_repos=[], non_shipping_repos=[]):
'Generates a valid content_sets.yml file based on the currently\n configured and enabled repos in the collection. Using the correct\n name for each arch.'
missing_repos = (set(enabled_repos) - self._repos.keys())
if missing_repos:
raise ValueError(f'enabled_repos references undefined repo(s): {missing_repos}')
result = {}
globally_enabled_repos = {r.name for r in self._repos.values() if r.enabled}
shipping_repos = ((set(globally_enabled_repos) | set(enabled_repos)) - set(non_shipping_repos))
for a in self._arches:
content_sets = []
for r in shipping_repos:
cs = self._repos[r].content_set(a)
if cs:
content_sets.append(cs)
if content_sets:
result[a] = content_sets
return (CONTENT_SETS + yaml.dump(result, default_flow_style=False))
|
Generates a valid content_sets.yml file based on the currently
configured and enabled repos in the collection. Using the correct
name for each arch.
|
doozerlib/repos.py
|
content_sets
|
Ximinhan/doozer
| 16 |
python
|
def content_sets(self, enabled_repos=[], non_shipping_repos=[]):
'Generates a valid content_sets.yml file based on the currently\n configured and enabled repos in the collection. Using the correct\n name for each arch.'
missing_repos = (set(enabled_repos) - self._repos.keys())
if missing_repos:
raise ValueError(f'enabled_repos references undefined repo(s): {missing_repos}')
result = {}
globally_enabled_repos = {r.name for r in self._repos.values() if r.enabled}
shipping_repos = ((set(globally_enabled_repos) | set(enabled_repos)) - set(non_shipping_repos))
for a in self._arches:
content_sets = []
for r in shipping_repos:
cs = self._repos[r].content_set(a)
if cs:
content_sets.append(cs)
if content_sets:
result[a] = content_sets
return (CONTENT_SETS + yaml.dump(result, default_flow_style=False))
|
def content_sets(self, enabled_repos=[], non_shipping_repos=[]):
'Generates a valid content_sets.yml file based on the currently\n configured and enabled repos in the collection. Using the correct\n name for each arch.'
missing_repos = (set(enabled_repos) - self._repos.keys())
if missing_repos:
raise ValueError(f'enabled_repos references undefined repo(s): {missing_repos}')
result = {}
globally_enabled_repos = {r.name for r in self._repos.values() if r.enabled}
shipping_repos = ((set(globally_enabled_repos) | set(enabled_repos)) - set(non_shipping_repos))
for a in self._arches:
content_sets = []
for r in shipping_repos:
cs = self._repos[r].content_set(a)
if cs:
content_sets.append(cs)
if content_sets:
result[a] = content_sets
return (CONTENT_SETS + yaml.dump(result, default_flow_style=False))<|docstring|>Generates a valid content_sets.yml file based on the currently
configured and enabled repos in the collection. Using the correct
name for each arch.<|endoftext|>
|
45ac49469514ad81e3503cbb838bc433378be53a35e6aabe26c97abe678a0cce
|
def get_dspec(filename, doplot=False, vmax=None, vmin=None, norm=None, cmap=None):
"\n Read EOVSA Dynamic Spectrum FITS file <filename> and return a spectrogram dictionary.\n Optionally show an overview plot if doplot switch is set.\n\n Example:\n --------\n >>> from suncasa.eovsa import eovsa_dspec as ds\n >>> from astropy.time import Time\n >>> from matplotlib.colors import LogNorm\n ## Read EOVSA Dynamic Spectrum FITS file <filename>\n >>> filename = 'EOVSA_TPall_20170713.fts'\n >>> s = ds.get_dspec(filename, doplot=True, cmap='gist_heat', norm=LogNorm(vmax=2.1e3, vmin=40))\n ## To access the data in the spectrogram object, use\n >>> spec = s['spectrogram'] ## (Array of amplitudes in SFU, of size nfreq,ntimes)\n >>> fghz = s['spectrum_axis'] ## (Array of frequencies in GHz, of size nfreq)\n >>> tim = Time(s['time_axis'], format='mjd') ## (Array of UT times in astropy.time object, of size ntimes)\n\n Parameters\n ----------\n filename : filename of the spectrogram fits file\n\n doplot : Boolean, optional\n\n vmin, vmax : scalar, optional\n When using scalar data and no explicit norm, vmin and vmax\n define the data range that the colormap covers. By default,\n the colormap covers the complete value range of the supplied data.\n vmin, vmax are ignored if the norm parameter is used.\n\n norm : `matplotib.colors Normalization object` or str, optional\n The Normalize instance used to scale scalar data to the [0, 1]\n range before mapping to colors using cmap. By default, a linear\n scaling mapping the lowest value to 0 and the highest to 1 is used.\n This parameter is ignored for RGB(A) data.\n\n cmap : `matplotib.colors.Colormap` or str\n A colormap instance or the name of a registered colormap.\n\n Returns\n -------\n spectrogram : dictionary\n "
hdulist = fits.open(filename)
spec = hdulist[0].data
fghz = np.array(astropy.table.Table(hdulist[1].data)['sfreq'])
tim = astropy.table.Table(hdulist[2].data)
tmjd = (np.array(tim['mjd']) + (((np.array(tim['time']) / 24.0) / 3600) / 1000))
tim = Time(tmjd, format='mjd')
timplt = tim.plot_date
ntim = len(timplt)
nfreq = len(fghz)
if doplot:
(fig, ax) = plt.subplots(figsize=(7, 4))
pcm = ax.pcolormesh(timplt, fghz, spec, norm=norm, vmax=vmax, vmin=vmin, cmap=cmap, rasterized='True')
ax.xaxis_date()
ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))
ax.set_ylim(fghz[0], fghz[(- 1)])
ax.set_xlim(tim[0].plot_date, tim[(- 1)].plot_date)
ax.set_xlabel('Time [UT]')
ax.set_ylabel('Frequency [GHz]')
ax.set_title(('EOVSA Dynamic Spectrum for ' + tim[0].datetime.strftime('%Y-%m-%d')))
divider = make_axes_locatable(ax)
cax_spec = divider.append_axes('right', size='1.5%', pad=0.05)
clb_spec = plt.colorbar(pcm, ax=ax, cax=cax_spec, label='Flux density [sfu]')
cmap = pcm.get_cmap()
bkg_facecolor = cmap(0.0)
ax.set_facecolor(bkg_facecolor)
dtim = np.diff(tmjd)
idxs_tgap = np.where((((dtim * 24) * 60) >= 0.5))[0]
if (len(idxs_tgap) > 0):
for idx in idxs_tgap:
if ((idx + 1) < len(tmjd)):
ax.axvspan(tim[idx].plot_date, tim[(idx + 1)].plot_date, facecolor=bkg_facecolor, edgecolor='none')
def format_coord(x, y):
col = np.argmin(np.absolute((timplt - x)))
row = np.argmin(np.absolute((fghz - y)))
if ((col >= 0) and (col < ntim) and (row >= 0) and (row < nfreq)):
timstr = tim[col].isot
flux = spec[(row, col)]
return 'time {0}, freq = {1:.3f} GHz, flux = {2:.2f} sfu'.format(timstr, y, flux)
else:
return 'x = {0}, y = {1:.3f}'.format(x, y)
ax.format_coord = format_coord
fig.tight_layout()
plt.show()
return {'spectrogram': spec, 'spectrum_axis': fghz, 'time_axis': tmjd}
|
Read EOVSA Dynamic Spectrum FITS file <filename> and return a spectrogram dictionary.
Optionally show an overview plot if doplot switch is set.
Example:
--------
>>> from suncasa.eovsa import eovsa_dspec as ds
>>> from astropy.time import Time
>>> from matplotlib.colors import LogNorm
## Read EOVSA Dynamic Spectrum FITS file <filename>
>>> filename = 'EOVSA_TPall_20170713.fts'
>>> s = ds.get_dspec(filename, doplot=True, cmap='gist_heat', norm=LogNorm(vmax=2.1e3, vmin=40))
## To access the data in the spectrogram object, use
>>> spec = s['spectrogram'] ## (Array of amplitudes in SFU, of size nfreq,ntimes)
>>> fghz = s['spectrum_axis'] ## (Array of frequencies in GHz, of size nfreq)
>>> tim = Time(s['time_axis'], format='mjd') ## (Array of UT times in astropy.time object, of size ntimes)
Parameters
----------
filename : filename of the spectrogram fits file
doplot : Boolean, optional
vmin, vmax : scalar, optional
When using scalar data and no explicit norm, vmin and vmax
define the data range that the colormap covers. By default,
the colormap covers the complete value range of the supplied data.
vmin, vmax are ignored if the norm parameter is used.
norm : `matplotib.colors Normalization object` or str, optional
The Normalize instance used to scale scalar data to the [0, 1]
range before mapping to colors using cmap. By default, a linear
scaling mapping the lowest value to 0 and the highest to 1 is used.
This parameter is ignored for RGB(A) data.
cmap : `matplotib.colors.Colormap` or str
A colormap instance or the name of a registered colormap.
Returns
-------
spectrogram : dictionary
|
suncasa/eovsa/eovsa_dspec.py
|
get_dspec
|
wyq24/suncasa
| 7 |
python
|
def get_dspec(filename, doplot=False, vmax=None, vmin=None, norm=None, cmap=None):
"\n Read EOVSA Dynamic Spectrum FITS file <filename> and return a spectrogram dictionary.\n Optionally show an overview plot if doplot switch is set.\n\n Example:\n --------\n >>> from suncasa.eovsa import eovsa_dspec as ds\n >>> from astropy.time import Time\n >>> from matplotlib.colors import LogNorm\n ## Read EOVSA Dynamic Spectrum FITS file <filename>\n >>> filename = 'EOVSA_TPall_20170713.fts'\n >>> s = ds.get_dspec(filename, doplot=True, cmap='gist_heat', norm=LogNorm(vmax=2.1e3, vmin=40))\n ## To access the data in the spectrogram object, use\n >>> spec = s['spectrogram'] ## (Array of amplitudes in SFU, of size nfreq,ntimes)\n >>> fghz = s['spectrum_axis'] ## (Array of frequencies in GHz, of size nfreq)\n >>> tim = Time(s['time_axis'], format='mjd') ## (Array of UT times in astropy.time object, of size ntimes)\n\n Parameters\n ----------\n filename : filename of the spectrogram fits file\n\n doplot : Boolean, optional\n\n vmin, vmax : scalar, optional\n When using scalar data and no explicit norm, vmin and vmax\n define the data range that the colormap covers. By default,\n the colormap covers the complete value range of the supplied data.\n vmin, vmax are ignored if the norm parameter is used.\n\n norm : `matplotib.colors Normalization object` or str, optional\n The Normalize instance used to scale scalar data to the [0, 1]\n range before mapping to colors using cmap. By default, a linear\n scaling mapping the lowest value to 0 and the highest to 1 is used.\n This parameter is ignored for RGB(A) data.\n\n cmap : `matplotib.colors.Colormap` or str\n A colormap instance or the name of a registered colormap.\n\n Returns\n -------\n spectrogram : dictionary\n "
hdulist = fits.open(filename)
spec = hdulist[0].data
fghz = np.array(astropy.table.Table(hdulist[1].data)['sfreq'])
tim = astropy.table.Table(hdulist[2].data)
tmjd = (np.array(tim['mjd']) + (((np.array(tim['time']) / 24.0) / 3600) / 1000))
tim = Time(tmjd, format='mjd')
timplt = tim.plot_date
ntim = len(timplt)
nfreq = len(fghz)
if doplot:
(fig, ax) = plt.subplots(figsize=(7, 4))
pcm = ax.pcolormesh(timplt, fghz, spec, norm=norm, vmax=vmax, vmin=vmin, cmap=cmap, rasterized='True')
ax.xaxis_date()
ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))
ax.set_ylim(fghz[0], fghz[(- 1)])
ax.set_xlim(tim[0].plot_date, tim[(- 1)].plot_date)
ax.set_xlabel('Time [UT]')
ax.set_ylabel('Frequency [GHz]')
ax.set_title(('EOVSA Dynamic Spectrum for ' + tim[0].datetime.strftime('%Y-%m-%d')))
divider = make_axes_locatable(ax)
cax_spec = divider.append_axes('right', size='1.5%', pad=0.05)
clb_spec = plt.colorbar(pcm, ax=ax, cax=cax_spec, label='Flux density [sfu]')
cmap = pcm.get_cmap()
bkg_facecolor = cmap(0.0)
ax.set_facecolor(bkg_facecolor)
dtim = np.diff(tmjd)
idxs_tgap = np.where((((dtim * 24) * 60) >= 0.5))[0]
if (len(idxs_tgap) > 0):
for idx in idxs_tgap:
if ((idx + 1) < len(tmjd)):
ax.axvspan(tim[idx].plot_date, tim[(idx + 1)].plot_date, facecolor=bkg_facecolor, edgecolor='none')
def format_coord(x, y):
col = np.argmin(np.absolute((timplt - x)))
row = np.argmin(np.absolute((fghz - y)))
if ((col >= 0) and (col < ntim) and (row >= 0) and (row < nfreq)):
timstr = tim[col].isot
flux = spec[(row, col)]
return 'time {0}, freq = {1:.3f} GHz, flux = {2:.2f} sfu'.format(timstr, y, flux)
else:
return 'x = {0}, y = {1:.3f}'.format(x, y)
ax.format_coord = format_coord
fig.tight_layout()
plt.show()
return {'spectrogram': spec, 'spectrum_axis': fghz, 'time_axis': tmjd}
|
def get_dspec(filename, doplot=False, vmax=None, vmin=None, norm=None, cmap=None):
"\n Read EOVSA Dynamic Spectrum FITS file <filename> and return a spectrogram dictionary.\n Optionally show an overview plot if doplot switch is set.\n\n Example:\n --------\n >>> from suncasa.eovsa import eovsa_dspec as ds\n >>> from astropy.time import Time\n >>> from matplotlib.colors import LogNorm\n ## Read EOVSA Dynamic Spectrum FITS file <filename>\n >>> filename = 'EOVSA_TPall_20170713.fts'\n >>> s = ds.get_dspec(filename, doplot=True, cmap='gist_heat', norm=LogNorm(vmax=2.1e3, vmin=40))\n ## To access the data in the spectrogram object, use\n >>> spec = s['spectrogram'] ## (Array of amplitudes in SFU, of size nfreq,ntimes)\n >>> fghz = s['spectrum_axis'] ## (Array of frequencies in GHz, of size nfreq)\n >>> tim = Time(s['time_axis'], format='mjd') ## (Array of UT times in astropy.time object, of size ntimes)\n\n Parameters\n ----------\n filename : filename of the spectrogram fits file\n\n doplot : Boolean, optional\n\n vmin, vmax : scalar, optional\n When using scalar data and no explicit norm, vmin and vmax\n define the data range that the colormap covers. By default,\n the colormap covers the complete value range of the supplied data.\n vmin, vmax are ignored if the norm parameter is used.\n\n norm : `matplotib.colors Normalization object` or str, optional\n The Normalize instance used to scale scalar data to the [0, 1]\n range before mapping to colors using cmap. By default, a linear\n scaling mapping the lowest value to 0 and the highest to 1 is used.\n This parameter is ignored for RGB(A) data.\n\n cmap : `matplotib.colors.Colormap` or str\n A colormap instance or the name of a registered colormap.\n\n Returns\n -------\n spectrogram : dictionary\n "
hdulist = fits.open(filename)
spec = hdulist[0].data
fghz = np.array(astropy.table.Table(hdulist[1].data)['sfreq'])
tim = astropy.table.Table(hdulist[2].data)
tmjd = (np.array(tim['mjd']) + (((np.array(tim['time']) / 24.0) / 3600) / 1000))
tim = Time(tmjd, format='mjd')
timplt = tim.plot_date
ntim = len(timplt)
nfreq = len(fghz)
if doplot:
(fig, ax) = plt.subplots(figsize=(7, 4))
pcm = ax.pcolormesh(timplt, fghz, spec, norm=norm, vmax=vmax, vmin=vmin, cmap=cmap, rasterized='True')
ax.xaxis_date()
ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))
ax.set_ylim(fghz[0], fghz[(- 1)])
ax.set_xlim(tim[0].plot_date, tim[(- 1)].plot_date)
ax.set_xlabel('Time [UT]')
ax.set_ylabel('Frequency [GHz]')
ax.set_title(('EOVSA Dynamic Spectrum for ' + tim[0].datetime.strftime('%Y-%m-%d')))
divider = make_axes_locatable(ax)
cax_spec = divider.append_axes('right', size='1.5%', pad=0.05)
clb_spec = plt.colorbar(pcm, ax=ax, cax=cax_spec, label='Flux density [sfu]')
cmap = pcm.get_cmap()
bkg_facecolor = cmap(0.0)
ax.set_facecolor(bkg_facecolor)
dtim = np.diff(tmjd)
idxs_tgap = np.where((((dtim * 24) * 60) >= 0.5))[0]
if (len(idxs_tgap) > 0):
for idx in idxs_tgap:
if ((idx + 1) < len(tmjd)):
ax.axvspan(tim[idx].plot_date, tim[(idx + 1)].plot_date, facecolor=bkg_facecolor, edgecolor='none')
def format_coord(x, y):
col = np.argmin(np.absolute((timplt - x)))
row = np.argmin(np.absolute((fghz - y)))
if ((col >= 0) and (col < ntim) and (row >= 0) and (row < nfreq)):
timstr = tim[col].isot
flux = spec[(row, col)]
return 'time {0}, freq = {1:.3f} GHz, flux = {2:.2f} sfu'.format(timstr, y, flux)
else:
return 'x = {0}, y = {1:.3f}'.format(x, y)
ax.format_coord = format_coord
fig.tight_layout()
plt.show()
return {'spectrogram': spec, 'spectrum_axis': fghz, 'time_axis': tmjd}<|docstring|>Read EOVSA Dynamic Spectrum FITS file <filename> and return a spectrogram dictionary.
Optionally show an overview plot if doplot switch is set.
Example:
--------
>>> from suncasa.eovsa import eovsa_dspec as ds
>>> from astropy.time import Time
>>> from matplotlib.colors import LogNorm
## Read EOVSA Dynamic Spectrum FITS file <filename>
>>> filename = 'EOVSA_TPall_20170713.fts'
>>> s = ds.get_dspec(filename, doplot=True, cmap='gist_heat', norm=LogNorm(vmax=2.1e3, vmin=40))
## To access the data in the spectrogram object, use
>>> spec = s['spectrogram'] ## (Array of amplitudes in SFU, of size nfreq,ntimes)
>>> fghz = s['spectrum_axis'] ## (Array of frequencies in GHz, of size nfreq)
>>> tim = Time(s['time_axis'], format='mjd') ## (Array of UT times in astropy.time object, of size ntimes)
Parameters
----------
filename : filename of the spectrogram fits file
doplot : Boolean, optional
vmin, vmax : scalar, optional
When using scalar data and no explicit norm, vmin and vmax
define the data range that the colormap covers. By default,
the colormap covers the complete value range of the supplied data.
vmin, vmax are ignored if the norm parameter is used.
norm : `matplotib.colors Normalization object` or str, optional
The Normalize instance used to scale scalar data to the [0, 1]
range before mapping to colors using cmap. By default, a linear
scaling mapping the lowest value to 0 and the highest to 1 is used.
This parameter is ignored for RGB(A) data.
cmap : `matplotib.colors.Colormap` or str
A colormap instance or the name of a registered colormap.
Returns
-------
spectrogram : dictionary<|endoftext|>
|
06d8f029517bb50bc7c4fceecb000cdf47ee90162676e339c23cac7ea20abacd
|
def focal_length_from_two_points(a, b, c, d):
'\n Brief: focal length from two points\n See appendex 6.1 Focal Length from Two Points\n :param a:\n :param b:\n :param c:\n :param d:\n :return: 0 (failed) or focal lenth in pixels\n '
c_2 = math.pow(c, 2)
d_2 = math.pow(d, 2)
t1 = (2 * (((d_2 * a) * b) - c_2))
t2 = (math.pow(((d_2 * (a + b)) - (2 * c)), 2) - ((4 * (((d_2 * a) * b) - c_2)) * (d_2 - 1)))
f = 0
if (t2 < 0):
print('warning: invalid focal length')
return f
assert (t2 >= 0)
t3 = (((2 * c) - (d_2 * (a + b))) + math.sqrt(t2))
if (t3 == 0):
print('warning: invalid focal length')
return f
assert (t3 != 0)
f2 = (t1 / t3)
if (f2 > 0):
f = math.sqrt(f2)
else:
print('warning: invalid focal length')
return f
|
Brief: focal length from two points
See appendex 6.1 Focal Length from Two Points
:param a:
:param b:
:param c:
:param d:
:return: 0 (failed) or focal lenth in pixels
|
python/util.py
|
focal_length_from_two_points
|
lood339/two_point_calib
| 45 |
python
|
def focal_length_from_two_points(a, b, c, d):
'\n Brief: focal length from two points\n See appendex 6.1 Focal Length from Two Points\n :param a:\n :param b:\n :param c:\n :param d:\n :return: 0 (failed) or focal lenth in pixels\n '
c_2 = math.pow(c, 2)
d_2 = math.pow(d, 2)
t1 = (2 * (((d_2 * a) * b) - c_2))
t2 = (math.pow(((d_2 * (a + b)) - (2 * c)), 2) - ((4 * (((d_2 * a) * b) - c_2)) * (d_2 - 1)))
f = 0
if (t2 < 0):
print('warning: invalid focal length')
return f
assert (t2 >= 0)
t3 = (((2 * c) - (d_2 * (a + b))) + math.sqrt(t2))
if (t3 == 0):
print('warning: invalid focal length')
return f
assert (t3 != 0)
f2 = (t1 / t3)
if (f2 > 0):
f = math.sqrt(f2)
else:
print('warning: invalid focal length')
return f
|
def focal_length_from_two_points(a, b, c, d):
'\n Brief: focal length from two points\n See appendex 6.1 Focal Length from Two Points\n :param a:\n :param b:\n :param c:\n :param d:\n :return: 0 (failed) or focal lenth in pixels\n '
c_2 = math.pow(c, 2)
d_2 = math.pow(d, 2)
t1 = (2 * (((d_2 * a) * b) - c_2))
t2 = (math.pow(((d_2 * (a + b)) - (2 * c)), 2) - ((4 * (((d_2 * a) * b) - c_2)) * (d_2 - 1)))
f = 0
if (t2 < 0):
print('warning: invalid focal length')
return f
assert (t2 >= 0)
t3 = (((2 * c) - (d_2 * (a + b))) + math.sqrt(t2))
if (t3 == 0):
print('warning: invalid focal length')
return f
assert (t3 != 0)
f2 = (t1 / t3)
if (f2 > 0):
f = math.sqrt(f2)
else:
print('warning: invalid focal length')
return f<|docstring|>Brief: focal length from two points
See appendex 6.1 Focal Length from Two Points
:param a:
:param b:
:param c:
:param d:
:return: 0 (failed) or focal lenth in pixels<|endoftext|>
|
a7a611d5e7ba4f1b8660a21f509830613953941e3195e1793727925a9a50a909
|
def pan_y_tilt_x(pan, tilt):
'\n matrix from pan Y along with axis then tilt along with X axis\n m = Q_\\phi * Q_\theta in equation (1)\n :param pan:\n :param tilt:\n :return:\n '
pan = ((pan * math.pi) / 180.0)
tilt = ((tilt * math.pi) / 180.0)
r_tilt = np.asarray([[1, 0, 0], [0, math.cos(tilt), math.sin(tilt)], [0, (- math.sin(tilt)), math.cos(tilt)]])
r_pan = np.asarray([[math.cos(pan), 0, (- math.sin(pan))], [0, 1, 0], [math.sin(pan), 0, math.cos(pan)]])
m = (r_tilt * r_pan)
return m
|
matrix from pan Y along with axis then tilt along with X axis
m = Q_\phi * Q_ heta in equation (1)
:param pan:
:param tilt:
:return:
|
python/util.py
|
pan_y_tilt_x
|
lood339/two_point_calib
| 45 |
python
|
def pan_y_tilt_x(pan, tilt):
'\n matrix from pan Y along with axis then tilt along with X axis\n m = Q_\\phi * Q_\theta in equation (1)\n :param pan:\n :param tilt:\n :return:\n '
pan = ((pan * math.pi) / 180.0)
tilt = ((tilt * math.pi) / 180.0)
r_tilt = np.asarray([[1, 0, 0], [0, math.cos(tilt), math.sin(tilt)], [0, (- math.sin(tilt)), math.cos(tilt)]])
r_pan = np.asarray([[math.cos(pan), 0, (- math.sin(pan))], [0, 1, 0], [math.sin(pan), 0, math.cos(pan)]])
m = (r_tilt * r_pan)
return m
|
def pan_y_tilt_x(pan, tilt):
'\n matrix from pan Y along with axis then tilt along with X axis\n m = Q_\\phi * Q_\theta in equation (1)\n :param pan:\n :param tilt:\n :return:\n '
pan = ((pan * math.pi) / 180.0)
tilt = ((tilt * math.pi) / 180.0)
r_tilt = np.asarray([[1, 0, 0], [0, math.cos(tilt), math.sin(tilt)], [0, (- math.sin(tilt)), math.cos(tilt)]])
r_pan = np.asarray([[math.cos(pan), 0, (- math.sin(pan))], [0, 1, 0], [math.sin(pan), 0, math.cos(pan)]])
m = (r_tilt * r_pan)
return m<|docstring|>matrix from pan Y along with axis then tilt along with X axis
m = Q_\phi * Q_ heta in equation (1)
:param pan:
:param tilt:
:return:<|endoftext|>
|
a6040d66e6d77ea8357b0abaf87658e474ea87c9bd7ee4d467e96b55f3f54284
|
def ptz_from_two_point(principal_point, pan_tilt1, pan_tilt2, point1, point2):
'\n Estimate pan, tilt and zoom from two points\n See Section 3.1 Two-point Algorithm for Data Annotation\n :param principal_point: [u, v], e.g image center, 2 x 1, numpy array\n :param pan_tilt1: pan and tile of point1, unit degress\n :param pan_tilt2: same as pan_tilt1,\n :param point1: point 1 location, unit pixel, 2 x 1, numpy array\n :param point2: same as point1\n :return: None if fail, otherwise, pan_tilt_focal_length\n '
p1 = (point1 - principal_point)
p2 = (point2 - principal_point)
a = np.dot(p1, p1)
b = np.dot(p2, p2)
c = np.dot(p1, p2)
z = np.asarray([0, 0, 1])
(pan1, tilt1) = (pan_tilt1[0], pan_tilt1[1])
(pan2, tilt2) = (pan_tilt2[0], pan_tilt2[1])
pan_tilt_z = np.matmul(pan_y_tilt_x((pan2 - pan1), (tilt2 - tilt1)), z)
d = np.dot(z, pan_tilt_z)
f = focal_length_from_two_points(a, b, c, d)
if (f <= 0):
print('Warning: estimate focal length failed')
return None
ptz = np.zeros(3)
pi = math.pi
theta1 = (pan1 - ((math.atan2(p1[0], f) * 180.0) / pi))
theta2 = (pan2 - ((math.atan2(p2[0], f) * 180.0) / pi))
ptz[0] = ((theta1 + theta2) / 2.0)
phi1 = (tilt1 - ((math.atan2(p1[1], f) * 180.0) / pi))
phi2 = (tilt2 - ((math.atan2(p2[1], f) * 180.0) / pi))
ptz[1] = ((phi1 + phi2) / 2.0)
ptz[2] = f
return ptz
|
Estimate pan, tilt and zoom from two points
See Section 3.1 Two-point Algorithm for Data Annotation
:param principal_point: [u, v], e.g image center, 2 x 1, numpy array
:param pan_tilt1: pan and tile of point1, unit degress
:param pan_tilt2: same as pan_tilt1,
:param point1: point 1 location, unit pixel, 2 x 1, numpy array
:param point2: same as point1
:return: None if fail, otherwise, pan_tilt_focal_length
|
python/util.py
|
ptz_from_two_point
|
lood339/two_point_calib
| 45 |
python
|
def ptz_from_two_point(principal_point, pan_tilt1, pan_tilt2, point1, point2):
'\n Estimate pan, tilt and zoom from two points\n See Section 3.1 Two-point Algorithm for Data Annotation\n :param principal_point: [u, v], e.g image center, 2 x 1, numpy array\n :param pan_tilt1: pan and tile of point1, unit degress\n :param pan_tilt2: same as pan_tilt1,\n :param point1: point 1 location, unit pixel, 2 x 1, numpy array\n :param point2: same as point1\n :return: None if fail, otherwise, pan_tilt_focal_length\n '
p1 = (point1 - principal_point)
p2 = (point2 - principal_point)
a = np.dot(p1, p1)
b = np.dot(p2, p2)
c = np.dot(p1, p2)
z = np.asarray([0, 0, 1])
(pan1, tilt1) = (pan_tilt1[0], pan_tilt1[1])
(pan2, tilt2) = (pan_tilt2[0], pan_tilt2[1])
pan_tilt_z = np.matmul(pan_y_tilt_x((pan2 - pan1), (tilt2 - tilt1)), z)
d = np.dot(z, pan_tilt_z)
f = focal_length_from_two_points(a, b, c, d)
if (f <= 0):
print('Warning: estimate focal length failed')
return None
ptz = np.zeros(3)
pi = math.pi
theta1 = (pan1 - ((math.atan2(p1[0], f) * 180.0) / pi))
theta2 = (pan2 - ((math.atan2(p2[0], f) * 180.0) / pi))
ptz[0] = ((theta1 + theta2) / 2.0)
phi1 = (tilt1 - ((math.atan2(p1[1], f) * 180.0) / pi))
phi2 = (tilt2 - ((math.atan2(p2[1], f) * 180.0) / pi))
ptz[1] = ((phi1 + phi2) / 2.0)
ptz[2] = f
return ptz
|
def ptz_from_two_point(principal_point, pan_tilt1, pan_tilt2, point1, point2):
'\n Estimate pan, tilt and zoom from two points\n See Section 3.1 Two-point Algorithm for Data Annotation\n :param principal_point: [u, v], e.g image center, 2 x 1, numpy array\n :param pan_tilt1: pan and tile of point1, unit degress\n :param pan_tilt2: same as pan_tilt1,\n :param point1: point 1 location, unit pixel, 2 x 1, numpy array\n :param point2: same as point1\n :return: None if fail, otherwise, pan_tilt_focal_length\n '
p1 = (point1 - principal_point)
p2 = (point2 - principal_point)
a = np.dot(p1, p1)
b = np.dot(p2, p2)
c = np.dot(p1, p2)
z = np.asarray([0, 0, 1])
(pan1, tilt1) = (pan_tilt1[0], pan_tilt1[1])
(pan2, tilt2) = (pan_tilt2[0], pan_tilt2[1])
pan_tilt_z = np.matmul(pan_y_tilt_x((pan2 - pan1), (tilt2 - tilt1)), z)
d = np.dot(z, pan_tilt_z)
f = focal_length_from_two_points(a, b, c, d)
if (f <= 0):
print('Warning: estimate focal length failed')
return None
ptz = np.zeros(3)
pi = math.pi
theta1 = (pan1 - ((math.atan2(p1[0], f) * 180.0) / pi))
theta2 = (pan2 - ((math.atan2(p2[0], f) * 180.0) / pi))
ptz[0] = ((theta1 + theta2) / 2.0)
phi1 = (tilt1 - ((math.atan2(p1[1], f) * 180.0) / pi))
phi2 = (tilt2 - ((math.atan2(p2[1], f) * 180.0) / pi))
ptz[1] = ((phi1 + phi2) / 2.0)
ptz[2] = f
return ptz<|docstring|>Estimate pan, tilt and zoom from two points
See Section 3.1 Two-point Algorithm for Data Annotation
:param principal_point: [u, v], e.g image center, 2 x 1, numpy array
:param pan_tilt1: pan and tile of point1, unit degress
:param pan_tilt2: same as pan_tilt1,
:param point1: point 1 location, unit pixel, 2 x 1, numpy array
:param point2: same as point1
:return: None if fail, otherwise, pan_tilt_focal_length<|endoftext|>
|
ab9028e35a4c3efaae7e7263a71e5fc5a12918cdca47faceb31588903c132871
|
def pan_tilt_from_principle_point(pp, pp_ptz, p):
'\n generate pan_tilt sample points using ptz ground truth\n :param pp: pincipal point\n :param pp_ptz: pincipal point pan, tilt zoom, eg. ptz of the image\n :param p: a point in the image, unit pixel\n :return: return value, pan and tilt\n '
dx = (p[0] - pp[0])
dy = (p[1] - pp[1])
pan_pp = pp_ptz[0]
tilt_pp = pp_ptz[1]
fl = pp_ptz[2]
delta_pan = ((math.atan2(dx, fl) * 180) / math.pi)
delta_tilt = ((math.atan2(dy, fl) * 180) / math.pi)
pt = np.zeros((2, 1))
pt[0] = (pan_pp + delta_pan)
pt[1] = (tilt_pp + delta_tilt)
return pt
|
generate pan_tilt sample points using ptz ground truth
:param pp: pincipal point
:param pp_ptz: pincipal point pan, tilt zoom, eg. ptz of the image
:param p: a point in the image, unit pixel
:return: return value, pan and tilt
|
python/util.py
|
pan_tilt_from_principle_point
|
lood339/two_point_calib
| 45 |
python
|
def pan_tilt_from_principle_point(pp, pp_ptz, p):
'\n generate pan_tilt sample points using ptz ground truth\n :param pp: pincipal point\n :param pp_ptz: pincipal point pan, tilt zoom, eg. ptz of the image\n :param p: a point in the image, unit pixel\n :return: return value, pan and tilt\n '
dx = (p[0] - pp[0])
dy = (p[1] - pp[1])
pan_pp = pp_ptz[0]
tilt_pp = pp_ptz[1]
fl = pp_ptz[2]
delta_pan = ((math.atan2(dx, fl) * 180) / math.pi)
delta_tilt = ((math.atan2(dy, fl) * 180) / math.pi)
pt = np.zeros((2, 1))
pt[0] = (pan_pp + delta_pan)
pt[1] = (tilt_pp + delta_tilt)
return pt
|
def pan_tilt_from_principle_point(pp, pp_ptz, p):
'\n generate pan_tilt sample points using ptz ground truth\n :param pp: pincipal point\n :param pp_ptz: pincipal point pan, tilt zoom, eg. ptz of the image\n :param p: a point in the image, unit pixel\n :return: return value, pan and tilt\n '
dx = (p[0] - pp[0])
dy = (p[1] - pp[1])
pan_pp = pp_ptz[0]
tilt_pp = pp_ptz[1]
fl = pp_ptz[2]
delta_pan = ((math.atan2(dx, fl) * 180) / math.pi)
delta_tilt = ((math.atan2(dy, fl) * 180) / math.pi)
pt = np.zeros((2, 1))
pt[0] = (pan_pp + delta_pan)
pt[1] = (tilt_pp + delta_tilt)
return pt<|docstring|>generate pan_tilt sample points using ptz ground truth
:param pp: pincipal point
:param pp_ptz: pincipal point pan, tilt zoom, eg. ptz of the image
:param p: a point in the image, unit pixel
:return: return value, pan and tilt<|endoftext|>
|
ea30c1efdc0a5c7fab914a149f78822b66becf6582557d589f1ce1d15e08c006
|
def test_execute_query_command(mocker):
"\n Given:\n - A LogAnalytics client object\n When:\n - Calling function execute_query_command\n Then:\n - Ensure the readable output's title is correct\n - Ensure the output's structure is as expected\n "
client = mock_client()
args = {}
mocker.patch.object(client, 'http_request', return_value=MOCKED_EXECUTE_QUERY_OUTPUT)
command_result = execute_query_command(client, args=args)
assert ('Query Results' in command_result.readable_output)
assert (len(command_result.outputs) == 2)
assert (command_result.outputs[0].get('TableName') == 'Table 1')
assert (command_result.outputs[1].get('Data')[1].get('column4') == 4)
|
Given:
- A LogAnalytics client object
When:
- Calling function execute_query_command
Then:
- Ensure the readable output's title is correct
- Ensure the output's structure is as expected
|
Packs/AzureLogAnalytics/Integrations/AzureLogAnalytics/AzureLogAnalytics_test.py
|
test_execute_query_command
|
ShacharKidor/content
| 799 |
python
|
def test_execute_query_command(mocker):
"\n Given:\n - A LogAnalytics client object\n When:\n - Calling function execute_query_command\n Then:\n - Ensure the readable output's title is correct\n - Ensure the output's structure is as expected\n "
client = mock_client()
args = {}
mocker.patch.object(client, 'http_request', return_value=MOCKED_EXECUTE_QUERY_OUTPUT)
command_result = execute_query_command(client, args=args)
assert ('Query Results' in command_result.readable_output)
assert (len(command_result.outputs) == 2)
assert (command_result.outputs[0].get('TableName') == 'Table 1')
assert (command_result.outputs[1].get('Data')[1].get('column4') == 4)
|
def test_execute_query_command(mocker):
"\n Given:\n - A LogAnalytics client object\n When:\n - Calling function execute_query_command\n Then:\n - Ensure the readable output's title is correct\n - Ensure the output's structure is as expected\n "
client = mock_client()
args = {}
mocker.patch.object(client, 'http_request', return_value=MOCKED_EXECUTE_QUERY_OUTPUT)
command_result = execute_query_command(client, args=args)
assert ('Query Results' in command_result.readable_output)
assert (len(command_result.outputs) == 2)
assert (command_result.outputs[0].get('TableName') == 'Table 1')
assert (command_result.outputs[1].get('Data')[1].get('column4') == 4)<|docstring|>Given:
- A LogAnalytics client object
When:
- Calling function execute_query_command
Then:
- Ensure the readable output's title is correct
- Ensure the output's structure is as expected<|endoftext|>
|
ff815b047311027516b1b9c629c77b7389aa8170189c053ce230e39715b9b12f
|
def test_list_saved_searches_command(mocker):
"\n Given:\n - A LogAnalytics client object\n - Arguments of azure-log-analytics-list-saved-searches command, representing we want\n a single saved search from the first page of the list to be retrieved\n When:\n - Calling function list_saved_searches_command\n Then:\n - Ensure the readable output's title is correct\n - Ensure a single saved search is returned\n - Ensure the output's structure is as expected\n "
client = mock_client()
args = {'limit': '1', 'page': '0'}
mocker.patch.object(client, 'http_request', return_value=MOCKED_SAVED_SEARCHES_OUTPUT)
command_result = list_saved_searches_command(client, args=args)
assert ('Saved searches' in command_result.readable_output)
assert (len(command_result.outputs) == 1)
assert (command_result.outputs[0].get('id') == 'mocked_saved_search')
assert (command_result.outputs[0].get('query') == 'mocked_query')
assert (command_result.outputs[0].get('displayName') == 'mocked saved search')
|
Given:
- A LogAnalytics client object
- Arguments of azure-log-analytics-list-saved-searches command, representing we want
a single saved search from the first page of the list to be retrieved
When:
- Calling function list_saved_searches_command
Then:
- Ensure the readable output's title is correct
- Ensure a single saved search is returned
- Ensure the output's structure is as expected
|
Packs/AzureLogAnalytics/Integrations/AzureLogAnalytics/AzureLogAnalytics_test.py
|
test_list_saved_searches_command
|
ShacharKidor/content
| 799 |
python
|
def test_list_saved_searches_command(mocker):
"\n Given:\n - A LogAnalytics client object\n - Arguments of azure-log-analytics-list-saved-searches command, representing we want\n a single saved search from the first page of the list to be retrieved\n When:\n - Calling function list_saved_searches_command\n Then:\n - Ensure the readable output's title is correct\n - Ensure a single saved search is returned\n - Ensure the output's structure is as expected\n "
client = mock_client()
args = {'limit': '1', 'page': '0'}
mocker.patch.object(client, 'http_request', return_value=MOCKED_SAVED_SEARCHES_OUTPUT)
command_result = list_saved_searches_command(client, args=args)
assert ('Saved searches' in command_result.readable_output)
assert (len(command_result.outputs) == 1)
assert (command_result.outputs[0].get('id') == 'mocked_saved_search')
assert (command_result.outputs[0].get('query') == 'mocked_query')
assert (command_result.outputs[0].get('displayName') == 'mocked saved search')
|
def test_list_saved_searches_command(mocker):
"\n Given:\n - A LogAnalytics client object\n - Arguments of azure-log-analytics-list-saved-searches command, representing we want\n a single saved search from the first page of the list to be retrieved\n When:\n - Calling function list_saved_searches_command\n Then:\n - Ensure the readable output's title is correct\n - Ensure a single saved search is returned\n - Ensure the output's structure is as expected\n "
client = mock_client()
args = {'limit': '1', 'page': '0'}
mocker.patch.object(client, 'http_request', return_value=MOCKED_SAVED_SEARCHES_OUTPUT)
command_result = list_saved_searches_command(client, args=args)
assert ('Saved searches' in command_result.readable_output)
assert (len(command_result.outputs) == 1)
assert (command_result.outputs[0].get('id') == 'mocked_saved_search')
assert (command_result.outputs[0].get('query') == 'mocked_query')
assert (command_result.outputs[0].get('displayName') == 'mocked saved search')<|docstring|>Given:
- A LogAnalytics client object
- Arguments of azure-log-analytics-list-saved-searches command, representing we want
a single saved search from the first page of the list to be retrieved
When:
- Calling function list_saved_searches_command
Then:
- Ensure the readable output's title is correct
- Ensure a single saved search is returned
- Ensure the output's structure is as expected<|endoftext|>
|
3ae2a2981b2485e3cb45ad7c71eee64be4a3aaaab4594837a9ed1c3ef310392a
|
def test_tags_arg_to_request_format():
'\n Given:\n - `tags` argument from azure-log-analytics-execute-query command\n - The argument has two tags (a name and a value for each tag)\n When:\n - Calling function tags_arg_to_request_format\n Then:\n - Ensure the argument is parsed correctly to a dict with two tags.\n '
tags_arg = 'name1=value1;name2=value2'
parsed_tags = tags_arg_to_request_format(tags_arg)
assert (len(parsed_tags) == 2)
assert (parsed_tags[0].get('name') == 'name1')
assert (parsed_tags[1].get('value') == 'value2')
|
Given:
- `tags` argument from azure-log-analytics-execute-query command
- The argument has two tags (a name and a value for each tag)
When:
- Calling function tags_arg_to_request_format
Then:
- Ensure the argument is parsed correctly to a dict with two tags.
|
Packs/AzureLogAnalytics/Integrations/AzureLogAnalytics/AzureLogAnalytics_test.py
|
test_tags_arg_to_request_format
|
ShacharKidor/content
| 799 |
python
|
def test_tags_arg_to_request_format():
'\n Given:\n - `tags` argument from azure-log-analytics-execute-query command\n - The argument has two tags (a name and a value for each tag)\n When:\n - Calling function tags_arg_to_request_format\n Then:\n - Ensure the argument is parsed correctly to a dict with two tags.\n '
tags_arg = 'name1=value1;name2=value2'
parsed_tags = tags_arg_to_request_format(tags_arg)
assert (len(parsed_tags) == 2)
assert (parsed_tags[0].get('name') == 'name1')
assert (parsed_tags[1].get('value') == 'value2')
|
def test_tags_arg_to_request_format():
'\n Given:\n - `tags` argument from azure-log-analytics-execute-query command\n - The argument has two tags (a name and a value for each tag)\n When:\n - Calling function tags_arg_to_request_format\n Then:\n - Ensure the argument is parsed correctly to a dict with two tags.\n '
tags_arg = 'name1=value1;name2=value2'
parsed_tags = tags_arg_to_request_format(tags_arg)
assert (len(parsed_tags) == 2)
assert (parsed_tags[0].get('name') == 'name1')
assert (parsed_tags[1].get('value') == 'value2')<|docstring|>Given:
- `tags` argument from azure-log-analytics-execute-query command
- The argument has two tags (a name and a value for each tag)
When:
- Calling function tags_arg_to_request_format
Then:
- Ensure the argument is parsed correctly to a dict with two tags.<|endoftext|>
|
f6692a3a6e451045ac0d77b9067fa6831fe0ad5345fcfed2c86fd00cbe7aa0a3
|
def state(bot, update, user_data, chat_data):
"The major function of this bot. It would receive user's message and initiate \n a download thread/process."
user_data.update({'chat_id': update.message.chat_id, 'actualusername': str(update.message.from_user.username), 'userMessage': update.message.text})
logger.info('Actual username is %s.', str(update.message.from_user.username))
outDict = urlanalysisdirect(user_data=user_data, logger=logger)
if ((outDict['identified'] == True) and (outDict['ehUrl'] == True)):
Ttime = time.asctime(time.localtime())
threadName = '{0}.{1}'.format(str(update.message.from_user.username), Ttime)
t = Thread(target=downloadfunc, name=threadName, kwargs={'bot': bot, 'urlResultList': outDict['urlResultList'], 'logger': logger, 'chat_id': update.message.chat_id})
threadQ.put(t)
elif ((outDict['identified'] == True) and (outDict['magnetLink'] == True) and ((config.hasAria2 == True) or (config.hasQbittorrent == True))):
Ttime = time.asctime(time.localtime())
threadName = '{0}.{1}'.format(str(update.message.from_user.username), Ttime)
t = Thread(target=magnetLinkDownload, name=threadName, kwargs={'bot': bot, 'urlResultList': outDict['urlResultList'], 'logger': logger, 'chat_id': update.message.chat_id})
threadQ.put(t)
else:
pass
message = telegramMessage(bot=bot, chat_id=update.message.chat_id, messageContent=outDict['outputTextList'], messageType='message')
retryDocorator(message.messageSend())
return ConversationHandler.END
|
The major function of this bot. It would receive user's message and initiate
a download thread/process.
|
tgexhDLbot.py
|
state
|
egg0001/telegram-e-hentaiDL-bot
| 7 |
python
|
def state(bot, update, user_data, chat_data):
"The major function of this bot. It would receive user's message and initiate \n a download thread/process."
user_data.update({'chat_id': update.message.chat_id, 'actualusername': str(update.message.from_user.username), 'userMessage': update.message.text})
logger.info('Actual username is %s.', str(update.message.from_user.username))
outDict = urlanalysisdirect(user_data=user_data, logger=logger)
if ((outDict['identified'] == True) and (outDict['ehUrl'] == True)):
Ttime = time.asctime(time.localtime())
threadName = '{0}.{1}'.format(str(update.message.from_user.username), Ttime)
t = Thread(target=downloadfunc, name=threadName, kwargs={'bot': bot, 'urlResultList': outDict['urlResultList'], 'logger': logger, 'chat_id': update.message.chat_id})
threadQ.put(t)
elif ((outDict['identified'] == True) and (outDict['magnetLink'] == True) and ((config.hasAria2 == True) or (config.hasQbittorrent == True))):
Ttime = time.asctime(time.localtime())
threadName = '{0}.{1}'.format(str(update.message.from_user.username), Ttime)
t = Thread(target=magnetLinkDownload, name=threadName, kwargs={'bot': bot, 'urlResultList': outDict['urlResultList'], 'logger': logger, 'chat_id': update.message.chat_id})
threadQ.put(t)
else:
pass
message = telegramMessage(bot=bot, chat_id=update.message.chat_id, messageContent=outDict['outputTextList'], messageType='message')
retryDocorator(message.messageSend())
return ConversationHandler.END
|
def state(bot, update, user_data, chat_data):
"The major function of this bot. It would receive user's message and initiate \n a download thread/process."
user_data.update({'chat_id': update.message.chat_id, 'actualusername': str(update.message.from_user.username), 'userMessage': update.message.text})
logger.info('Actual username is %s.', str(update.message.from_user.username))
outDict = urlanalysisdirect(user_data=user_data, logger=logger)
if ((outDict['identified'] == True) and (outDict['ehUrl'] == True)):
Ttime = time.asctime(time.localtime())
threadName = '{0}.{1}'.format(str(update.message.from_user.username), Ttime)
t = Thread(target=downloadfunc, name=threadName, kwargs={'bot': bot, 'urlResultList': outDict['urlResultList'], 'logger': logger, 'chat_id': update.message.chat_id})
threadQ.put(t)
elif ((outDict['identified'] == True) and (outDict['magnetLink'] == True) and ((config.hasAria2 == True) or (config.hasQbittorrent == True))):
Ttime = time.asctime(time.localtime())
threadName = '{0}.{1}'.format(str(update.message.from_user.username), Ttime)
t = Thread(target=magnetLinkDownload, name=threadName, kwargs={'bot': bot, 'urlResultList': outDict['urlResultList'], 'logger': logger, 'chat_id': update.message.chat_id})
threadQ.put(t)
else:
pass
message = telegramMessage(bot=bot, chat_id=update.message.chat_id, messageContent=outDict['outputTextList'], messageType='message')
retryDocorator(message.messageSend())
return ConversationHandler.END<|docstring|>The major function of this bot. It would receive user's message and initiate
a download thread/process.<|endoftext|>
|
41b54c0333eaa998d84a7b5d2a5d079968d325f5ff15212b9602a536f64dd4ef
|
def threadContainor(threadQ, threadLimit=1):
"A simple thread/process containor daemon thread to limit the amount of the download \n process thus prevent e-hentai bans user's IP. The t = threadQ.get() would block this \n loop until it receive a user request sent by the bot's user interaction function."
threadCounter = 0
while True:
t = threadQ.get()
t.start()
threadCounter += 1
if (threadCounter == threadLimit):
t.join()
threadCounter = 0
|
A simple thread/process containor daemon thread to limit the amount of the download
process thus prevent e-hentai bans user's IP. The t = threadQ.get() would block this
loop until it receive a user request sent by the bot's user interaction function.
|
tgexhDLbot.py
|
threadContainor
|
egg0001/telegram-e-hentaiDL-bot
| 7 |
python
|
def threadContainor(threadQ, threadLimit=1):
"A simple thread/process containor daemon thread to limit the amount of the download \n process thus prevent e-hentai bans user's IP. The t = threadQ.get() would block this \n loop until it receive a user request sent by the bot's user interaction function."
threadCounter = 0
while True:
t = threadQ.get()
t.start()
threadCounter += 1
if (threadCounter == threadLimit):
t.join()
threadCounter = 0
|
def threadContainor(threadQ, threadLimit=1):
"A simple thread/process containor daemon thread to limit the amount of the download \n process thus prevent e-hentai bans user's IP. The t = threadQ.get() would block this \n loop until it receive a user request sent by the bot's user interaction function."
threadCounter = 0
while True:
t = threadQ.get()
t.start()
threadCounter += 1
if (threadCounter == threadLimit):
t.join()
threadCounter = 0<|docstring|>A simple thread/process containor daemon thread to limit the amount of the download
process thus prevent e-hentai bans user's IP. The t = threadQ.get() would block this
loop until it receive a user request sent by the bot's user interaction function.<|endoftext|>
|
93f5c533f6e9018a5eaac49c468c51523648e02361179d96769a5b2e0b5d6d4d
|
def magnetLinkDownload(bot, urlResultList, logger, chat_id):
'This function exploits xmlprc to send command to aria2c or qbittorrent'
logger.info('magnetLinkDownload initiated.')
if (config.hasQbittorrent == True):
torrentList = magnet.torrentDownloadqQbt(magnetLinkList=urlResultList, logger=logger)
else:
torrentList = magnet.torrentDownloadAria2c(magnetLinkList=urlResultList, logger=logger)
for torrent in torrentList:
messageList = []
messageList.append(usermessage.magnetResultMessage.format(torrent.hash))
tempFileList = []
if torrent.error:
messageList.append(torrent.error)
for file in torrent.fileList:
tempFileList.append(file)
if (len(tempFileList) >= 4):
for file in tempFileList:
messageList.append(file)
messageList.append(tempFileList)
tempFileList = []
if tempFileList:
for file in tempFileList:
messageList.append(file)
torrentMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=messageList, messageType='message')
retryDocorator(torrentMessage.messageSend())
|
This function exploits xmlprc to send command to aria2c or qbittorrent
|
tgexhDLbot.py
|
magnetLinkDownload
|
egg0001/telegram-e-hentaiDL-bot
| 7 |
python
|
def magnetLinkDownload(bot, urlResultList, logger, chat_id):
logger.info('magnetLinkDownload initiated.')
if (config.hasQbittorrent == True):
torrentList = magnet.torrentDownloadqQbt(magnetLinkList=urlResultList, logger=logger)
else:
torrentList = magnet.torrentDownloadAria2c(magnetLinkList=urlResultList, logger=logger)
for torrent in torrentList:
messageList = []
messageList.append(usermessage.magnetResultMessage.format(torrent.hash))
tempFileList = []
if torrent.error:
messageList.append(torrent.error)
for file in torrent.fileList:
tempFileList.append(file)
if (len(tempFileList) >= 4):
for file in tempFileList:
messageList.append(file)
messageList.append(tempFileList)
tempFileList = []
if tempFileList:
for file in tempFileList:
messageList.append(file)
torrentMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=messageList, messageType='message')
retryDocorator(torrentMessage.messageSend())
|
def magnetLinkDownload(bot, urlResultList, logger, chat_id):
logger.info('magnetLinkDownload initiated.')
if (config.hasQbittorrent == True):
torrentList = magnet.torrentDownloadqQbt(magnetLinkList=urlResultList, logger=logger)
else:
torrentList = magnet.torrentDownloadAria2c(magnetLinkList=urlResultList, logger=logger)
for torrent in torrentList:
messageList = []
messageList.append(usermessage.magnetResultMessage.format(torrent.hash))
tempFileList = []
if torrent.error:
messageList.append(torrent.error)
for file in torrent.fileList:
tempFileList.append(file)
if (len(tempFileList) >= 4):
for file in tempFileList:
messageList.append(file)
messageList.append(tempFileList)
tempFileList = []
if tempFileList:
for file in tempFileList:
messageList.append(file)
torrentMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=messageList, messageType='message')
retryDocorator(torrentMessage.messageSend())<|docstring|>This function exploits xmlprc to send command to aria2c or qbittorrent<|endoftext|>
|
9eb5ab675a9010e9a8c1e861e4621b345cd7507ac27f82e62f43dbc8ddc502a0
|
def downloadfunc(bot, urlResultList, logger, chat_id):
" The bot's major function would call this download and result \n sending function to deal with user's requests."
mangaObjList = ehdownloader(urlResultList=urlResultList, logger=logger)
logger.info('Begin to send download result(s).')
for manga in mangaObjList:
if (manga.title != 'errorStoreMangaObj'):
if manga.previewImage:
photoMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[manga.previewImage], messageType='photo')
retryDocorator(photoMessage.photoSend())
textMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[manga.title], messageType='message')
retryDocorator(textMessage.messageSend())
try:
sendArchive = config.sendArchive
except:
sendArchive = False
if (sendArchive == True):
logger.info('Begin to send {0}. It should take a while.'.format(manga.title))
error = splitZip(path=config.path, category=manga.category, title=manga.title, url=manga.url, logger=logger)
if (error == None):
splitPath = '{0}{1}/split_{2}/'.format(config.path, manga.category, manga.title)
fileList = os.listdir(splitPath)
try:
for file in fileList:
snedFileT = Thread(target=sendFiles, name='sendFiles', kwargs={'bot': bot, 'fileDir': splitPath, 'fileName': file, 'logger': logger, 'chat_id': chat_id, 'manga': manga})
sendQ.put(snedFileT)
except Exception as e:
logger.Exception('Raise {0} while sending {1}'.format(e, manga.title))
error = e
else:
errorMsg = 'Raise {0} while sending {1}'.format(error, manga.title)
textMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[errorMsg], messageType='message')
retryDocorator(textMessage.messageSend())
else:
pass
if manga.dlErrorDict:
for error in manga.dlErrorDict:
errorMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[error, manga.dlErrorDict[error]], messageType='message')
retryDocorator(errorMessage.messageSend())
logger.info('All results has been sent.')
|
The bot's major function would call this download and result
sending function to deal with user's requests.
|
tgexhDLbot.py
|
downloadfunc
|
egg0001/telegram-e-hentaiDL-bot
| 7 |
python
|
def downloadfunc(bot, urlResultList, logger, chat_id):
" The bot's major function would call this download and result \n sending function to deal with user's requests."
mangaObjList = ehdownloader(urlResultList=urlResultList, logger=logger)
logger.info('Begin to send download result(s).')
for manga in mangaObjList:
if (manga.title != 'errorStoreMangaObj'):
if manga.previewImage:
photoMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[manga.previewImage], messageType='photo')
retryDocorator(photoMessage.photoSend())
textMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[manga.title], messageType='message')
retryDocorator(textMessage.messageSend())
try:
sendArchive = config.sendArchive
except:
sendArchive = False
if (sendArchive == True):
logger.info('Begin to send {0}. It should take a while.'.format(manga.title))
error = splitZip(path=config.path, category=manga.category, title=manga.title, url=manga.url, logger=logger)
if (error == None):
splitPath = '{0}{1}/split_{2}/'.format(config.path, manga.category, manga.title)
fileList = os.listdir(splitPath)
try:
for file in fileList:
snedFileT = Thread(target=sendFiles, name='sendFiles', kwargs={'bot': bot, 'fileDir': splitPath, 'fileName': file, 'logger': logger, 'chat_id': chat_id, 'manga': manga})
sendQ.put(snedFileT)
except Exception as e:
logger.Exception('Raise {0} while sending {1}'.format(e, manga.title))
error = e
else:
errorMsg = 'Raise {0} while sending {1}'.format(error, manga.title)
textMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[errorMsg], messageType='message')
retryDocorator(textMessage.messageSend())
else:
pass
if manga.dlErrorDict:
for error in manga.dlErrorDict:
errorMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[error, manga.dlErrorDict[error]], messageType='message')
retryDocorator(errorMessage.messageSend())
logger.info('All results has been sent.')
|
def downloadfunc(bot, urlResultList, logger, chat_id):
" The bot's major function would call this download and result \n sending function to deal with user's requests."
mangaObjList = ehdownloader(urlResultList=urlResultList, logger=logger)
logger.info('Begin to send download result(s).')
for manga in mangaObjList:
if (manga.title != 'errorStoreMangaObj'):
if manga.previewImage:
photoMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[manga.previewImage], messageType='photo')
retryDocorator(photoMessage.photoSend())
textMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[manga.title], messageType='message')
retryDocorator(textMessage.messageSend())
try:
sendArchive = config.sendArchive
except:
sendArchive = False
if (sendArchive == True):
logger.info('Begin to send {0}. It should take a while.'.format(manga.title))
error = splitZip(path=config.path, category=manga.category, title=manga.title, url=manga.url, logger=logger)
if (error == None):
splitPath = '{0}{1}/split_{2}/'.format(config.path, manga.category, manga.title)
fileList = os.listdir(splitPath)
try:
for file in fileList:
snedFileT = Thread(target=sendFiles, name='sendFiles', kwargs={'bot': bot, 'fileDir': splitPath, 'fileName': file, 'logger': logger, 'chat_id': chat_id, 'manga': manga})
sendQ.put(snedFileT)
except Exception as e:
logger.Exception('Raise {0} while sending {1}'.format(e, manga.title))
error = e
else:
errorMsg = 'Raise {0} while sending {1}'.format(error, manga.title)
textMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[errorMsg], messageType='message')
retryDocorator(textMessage.messageSend())
else:
pass
if manga.dlErrorDict:
for error in manga.dlErrorDict:
errorMessage = telegramMessage(bot=bot, chat_id=chat_id, messageContent=[error, manga.dlErrorDict[error]], messageType='message')
retryDocorator(errorMessage.messageSend())
logger.info('All results has been sent.')<|docstring|>The bot's major function would call this download and result
sending function to deal with user's requests.<|endoftext|>
|
f6530ad1ec584e495f9f02f70b21e4c73d6418554b7638543970532c1ee84e42
|
def retryDocorator(func, retry=config.messageTimeOutRetry):
'This simple retry decorator provides a try-except looping to the channelmessage function to\n overcome network fluctuation.'
@wraps(func)
def wrapperFunction(*args, **kwargs):
err = 0
for err in range(retry):
try:
func(*args, **kwargs)
break
except Exception as error:
err += 1
logger.warning(str(error))
else:
logger.warning('Retry limitation reached')
return None
return wrapperFunction
|
This simple retry decorator provides a try-except looping to the channelmessage function to
overcome network fluctuation.
|
tgexhDLbot.py
|
retryDocorator
|
egg0001/telegram-e-hentaiDL-bot
| 7 |
python
|
def retryDocorator(func, retry=config.messageTimeOutRetry):
'This simple retry decorator provides a try-except looping to the channelmessage function to\n overcome network fluctuation.'
@wraps(func)
def wrapperFunction(*args, **kwargs):
err = 0
for err in range(retry):
try:
func(*args, **kwargs)
break
except Exception as error:
err += 1
logger.warning(str(error))
else:
logger.warning('Retry limitation reached')
return None
return wrapperFunction
|
def retryDocorator(func, retry=config.messageTimeOutRetry):
'This simple retry decorator provides a try-except looping to the channelmessage function to\n overcome network fluctuation.'
@wraps(func)
def wrapperFunction(*args, **kwargs):
err = 0
for err in range(retry):
try:
func(*args, **kwargs)
break
except Exception as error:
err += 1
logger.warning(str(error))
else:
logger.warning('Retry limitation reached')
return None
return wrapperFunction<|docstring|>This simple retry decorator provides a try-except looping to the channelmessage function to
overcome network fluctuation.<|endoftext|>
|
05c692d80758543b495556bad75f966ec9cd2e4a83f9b8070b2ca7c12469dfd6
|
def cancel(bot, update, user_data, chat_data):
"Bot's cancel function, useless."
update.message.reply_text(text=usermessage.UserCancel)
logger.info('User %s has canceled the process.', str(update.message.from_user.username))
user_data.clear()
chat_data.clear()
logger.info('The user_data and chat_data of user %s has cleared', str(update.message.from_user.username))
return ConversationHandler.END
|
Bot's cancel function, useless.
|
tgexhDLbot.py
|
cancel
|
egg0001/telegram-e-hentaiDL-bot
| 7 |
python
|
def cancel(bot, update, user_data, chat_data):
update.message.reply_text(text=usermessage.UserCancel)
logger.info('User %s has canceled the process.', str(update.message.from_user.username))
user_data.clear()
chat_data.clear()
logger.info('The user_data and chat_data of user %s has cleared', str(update.message.from_user.username))
return ConversationHandler.END
|
def cancel(bot, update, user_data, chat_data):
update.message.reply_text(text=usermessage.UserCancel)
logger.info('User %s has canceled the process.', str(update.message.from_user.username))
user_data.clear()
chat_data.clear()
logger.info('The user_data and chat_data of user %s has cleared', str(update.message.from_user.username))
return ConversationHandler.END<|docstring|>Bot's cancel function, useless.<|endoftext|>
|
49c17e98596c72727a3846be82011ce98317c1d23f395ec4ae02c8fd2d2dbd31
|
def error(bot, update, error):
"Bot's error collecting function, may also be useless. "
logger.warning('Update "%s" caused error "%s"', update, error)
|
Bot's error collecting function, may also be useless.
|
tgexhDLbot.py
|
error
|
egg0001/telegram-e-hentaiDL-bot
| 7 |
python
|
def error(bot, update, error):
" "
logger.warning('Update "%s" caused error "%s"', update, error)
|
def error(bot, update, error):
" "
logger.warning('Update "%s" caused error "%s"', update, error)<|docstring|>Bot's error collecting function, may also be useless.<|endoftext|>
|
514725679dbf89ae26375323cdd7ac8d6b982a99749b80f92c681664740c5991
|
def main():
"The bot's initiation sequence."
if config.proxy:
if (config.proxy[0].find('@') != (- 1)):
proxyPattern = re.compile(regx.authProxyPattern)
proxyMatch = proxyPattern.search(config.proxy[0])
proxyAddress = '{0}://{1}:{2}'.format(proxyMatch.group(1), proxyMatch.group(4), proxyMatch.group(5))
proxyUsername = proxyMatch.group(2)
proxyPassword = proxyMatch.group(3)
updater = Updater(token=config.token, request_kwargs={'proxy_url': proxyAddress, 'urllib3_proxy_kwargs': {'username': proxyUsername, 'password': proxyPassword}})
else:
updater = Updater(token=config.token, request_kwargs={'proxy_url': config.proxy[0]})
else:
updater = Updater(token=config.token)
dp = updater.dispatcher
messageHandler = MessageHandler(Filters.text, state, pass_user_data=True, pass_chat_data=True)
dp.add_handler(messageHandler)
dp.add_error_handler(error)
updater.start_polling(poll_interval=1.0, timeout=1.0)
tc = Thread(target=threadContainor, name='tc', kwargs={'threadQ': threadQ}, daemon=True)
tc.start()
try:
sendArchive = config.sendArchive
except:
sendArchive = False
if (sendArchive == True):
stc = Thread(target=threadContainor, name='sat', kwargs={'threadQ': sendQ, 'threadLimit': 2}, daemon=True)
stc.start()
logger.info('trasnfer thread containor initiated.')
logger.info('Bot started.')
updater.idle()
|
The bot's initiation sequence.
|
tgexhDLbot.py
|
main
|
egg0001/telegram-e-hentaiDL-bot
| 7 |
python
|
def main():
if config.proxy:
if (config.proxy[0].find('@') != (- 1)):
proxyPattern = re.compile(regx.authProxyPattern)
proxyMatch = proxyPattern.search(config.proxy[0])
proxyAddress = '{0}://{1}:{2}'.format(proxyMatch.group(1), proxyMatch.group(4), proxyMatch.group(5))
proxyUsername = proxyMatch.group(2)
proxyPassword = proxyMatch.group(3)
updater = Updater(token=config.token, request_kwargs={'proxy_url': proxyAddress, 'urllib3_proxy_kwargs': {'username': proxyUsername, 'password': proxyPassword}})
else:
updater = Updater(token=config.token, request_kwargs={'proxy_url': config.proxy[0]})
else:
updater = Updater(token=config.token)
dp = updater.dispatcher
messageHandler = MessageHandler(Filters.text, state, pass_user_data=True, pass_chat_data=True)
dp.add_handler(messageHandler)
dp.add_error_handler(error)
updater.start_polling(poll_interval=1.0, timeout=1.0)
tc = Thread(target=threadContainor, name='tc', kwargs={'threadQ': threadQ}, daemon=True)
tc.start()
try:
sendArchive = config.sendArchive
except:
sendArchive = False
if (sendArchive == True):
stc = Thread(target=threadContainor, name='sat', kwargs={'threadQ': sendQ, 'threadLimit': 2}, daemon=True)
stc.start()
logger.info('trasnfer thread containor initiated.')
logger.info('Bot started.')
updater.idle()
|
def main():
if config.proxy:
if (config.proxy[0].find('@') != (- 1)):
proxyPattern = re.compile(regx.authProxyPattern)
proxyMatch = proxyPattern.search(config.proxy[0])
proxyAddress = '{0}://{1}:{2}'.format(proxyMatch.group(1), proxyMatch.group(4), proxyMatch.group(5))
proxyUsername = proxyMatch.group(2)
proxyPassword = proxyMatch.group(3)
updater = Updater(token=config.token, request_kwargs={'proxy_url': proxyAddress, 'urllib3_proxy_kwargs': {'username': proxyUsername, 'password': proxyPassword}})
else:
updater = Updater(token=config.token, request_kwargs={'proxy_url': config.proxy[0]})
else:
updater = Updater(token=config.token)
dp = updater.dispatcher
messageHandler = MessageHandler(Filters.text, state, pass_user_data=True, pass_chat_data=True)
dp.add_handler(messageHandler)
dp.add_error_handler(error)
updater.start_polling(poll_interval=1.0, timeout=1.0)
tc = Thread(target=threadContainor, name='tc', kwargs={'threadQ': threadQ}, daemon=True)
tc.start()
try:
sendArchive = config.sendArchive
except:
sendArchive = False
if (sendArchive == True):
stc = Thread(target=threadContainor, name='sat', kwargs={'threadQ': sendQ, 'threadLimit': 2}, daemon=True)
stc.start()
logger.info('trasnfer thread containor initiated.')
logger.info('Bot started.')
updater.idle()<|docstring|>The bot's initiation sequence.<|endoftext|>
|
eb63f5a9e07c85dd06fbc44e9799d1f92ebdf08a1af3dd572483c5172254b393
|
def get_by_path(root, items):
'Access a nested object in root by item sequence'
return reduce(operator.getitem, items, root)
|
Access a nested object in root by item sequence
|
junkdrawer/nested_dict_access_by_key_list.py
|
get_by_path
|
elegantmoose/junkdrawer
| 2 |
python
|
def get_by_path(root, items):
return reduce(operator.getitem, items, root)
|
def get_by_path(root, items):
return reduce(operator.getitem, items, root)<|docstring|>Access a nested object in root by item sequence<|endoftext|>
|
ae87c921aa7a738aba4fce80df56385dce1063d90711866bb2fc9c5ee6499172
|
def set_by_path(root, items, value):
'Set a value in a nested object in root by item sequence'
get_by_path(root, items[:(- 1)])[items[(- 1)]] = value
|
Set a value in a nested object in root by item sequence
|
junkdrawer/nested_dict_access_by_key_list.py
|
set_by_path
|
elegantmoose/junkdrawer
| 2 |
python
|
def set_by_path(root, items, value):
get_by_path(root, items[:(- 1)])[items[(- 1)]] = value
|
def set_by_path(root, items, value):
get_by_path(root, items[:(- 1)])[items[(- 1)]] = value<|docstring|>Set a value in a nested object in root by item sequence<|endoftext|>
|
99c0d9a79a8778ff84e280abd1fcf5f082d54355f5811466c2d4b6b5a59f3054
|
def in_nested_path(root, items):
" 'in' equivalent for a nested dict/list structure"
try:
get_by_path(root, items)
except KeyError:
return False
return True
|
'in' equivalent for a nested dict/list structure
|
junkdrawer/nested_dict_access_by_key_list.py
|
in_nested_path
|
elegantmoose/junkdrawer
| 2 |
python
|
def in_nested_path(root, items):
" "
try:
get_by_path(root, items)
except KeyError:
return False
return True
|
def in_nested_path(root, items):
" "
try:
get_by_path(root, items)
except KeyError:
return False
return True<|docstring|>'in' equivalent for a nested dict/list structure<|endoftext|>
|
b5af1c6cec6db7cd4c277b3c1f742eba451d49616febae94895daa1054592147
|
def get_anki_defaults(file_output=None, formatted=False):
'\n\n :param None|bool|str file_output:\n :param bool formatted:\n :return:\n '
if formatted:
default_filename = 'defaults_formatted.json'
else:
default_filename = 'defaults.json'
file_output = {None: None, False: None, True: module_path(default_filename)}.get(file_output, file_output)
defaults = OrderedDict()
with sqlite3.connect(get_collection_path()) as conn:
cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
for row in cursor:
table_name = row[0]
try:
defaults[table_name] = next(read_anki_table(conn, table_name))
except StopIteration:
defaults[table_name] = None
continue
if (formatted is not None):
for (k, v) in defaults[table_name].items():
if (formatted is True):
if isinstance(v, str):
try:
defaults[table_name][k] = {'is_json': True, 'data': json.loads(v, object_pairs_hook=OrderedDict)}
except JSONDecodeError:
pass
if (file_output is None):
print(json.dumps(defaults, indent=2))
else:
with open(file_output, 'w') as f:
json.dump(defaults, f, indent=2)
|
:param None|bool|str file_output:
:param bool formatted:
:return:
|
dev/get_anki_defaults.py
|
get_anki_defaults
|
patarapolw/AnkiTools
| 53 |
python
|
def get_anki_defaults(file_output=None, formatted=False):
'\n\n :param None|bool|str file_output:\n :param bool formatted:\n :return:\n '
if formatted:
default_filename = 'defaults_formatted.json'
else:
default_filename = 'defaults.json'
file_output = {None: None, False: None, True: module_path(default_filename)}.get(file_output, file_output)
defaults = OrderedDict()
with sqlite3.connect(get_collection_path()) as conn:
cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
for row in cursor:
table_name = row[0]
try:
defaults[table_name] = next(read_anki_table(conn, table_name))
except StopIteration:
defaults[table_name] = None
continue
if (formatted is not None):
for (k, v) in defaults[table_name].items():
if (formatted is True):
if isinstance(v, str):
try:
defaults[table_name][k] = {'is_json': True, 'data': json.loads(v, object_pairs_hook=OrderedDict)}
except JSONDecodeError:
pass
if (file_output is None):
print(json.dumps(defaults, indent=2))
else:
with open(file_output, 'w') as f:
json.dump(defaults, f, indent=2)
|
def get_anki_defaults(file_output=None, formatted=False):
'\n\n :param None|bool|str file_output:\n :param bool formatted:\n :return:\n '
if formatted:
default_filename = 'defaults_formatted.json'
else:
default_filename = 'defaults.json'
file_output = {None: None, False: None, True: module_path(default_filename)}.get(file_output, file_output)
defaults = OrderedDict()
with sqlite3.connect(get_collection_path()) as conn:
cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
for row in cursor:
table_name = row[0]
try:
defaults[table_name] = next(read_anki_table(conn, table_name))
except StopIteration:
defaults[table_name] = None
continue
if (formatted is not None):
for (k, v) in defaults[table_name].items():
if (formatted is True):
if isinstance(v, str):
try:
defaults[table_name][k] = {'is_json': True, 'data': json.loads(v, object_pairs_hook=OrderedDict)}
except JSONDecodeError:
pass
if (file_output is None):
print(json.dumps(defaults, indent=2))
else:
with open(file_output, 'w') as f:
json.dump(defaults, f, indent=2)<|docstring|>:param None|bool|str file_output:
:param bool formatted:
:return:<|endoftext|>
|
2c8b111074068a28e27d1fe0c3929f6290b7976beaa37c7defb2102667d62d6c
|
@property
def name(self):
'\n The name for the window as displayed in the title bar and status bar.\n '
if self.chosen_name:
return self.chosen_name
else:
name = self.process.get_name()
if name:
return os.path.basename(name)
return ''
|
The name for the window as displayed in the title bar and status bar.
|
pymux/arrangement.py
|
name
|
deepakbhilare/pymux
| 1,280 |
python
|
@property
def name(self):
'\n \n '
if self.chosen_name:
return self.chosen_name
else:
name = self.process.get_name()
if name:
return os.path.basename(name)
return
|
@property
def name(self):
'\n \n '
if self.chosen_name:
return self.chosen_name
else:
name = self.process.get_name()
if name:
return os.path.basename(name)
return <|docstring|>The name for the window as displayed in the title bar and status bar.<|endoftext|>
|
823e9a03f45465e4681986b1312f5425972b01e7aa2b58b488182685f3bec2f3
|
def enter_copy_mode(self):
'\n Suspend the process, and copy the screen content to the `scroll_buffer`.\n That way the user can search through the history and copy/paste.\n '
self.terminal.enter_copy_mode()
|
Suspend the process, and copy the screen content to the `scroll_buffer`.
That way the user can search through the history and copy/paste.
|
pymux/arrangement.py
|
enter_copy_mode
|
deepakbhilare/pymux
| 1,280 |
python
|
def enter_copy_mode(self):
'\n Suspend the process, and copy the screen content to the `scroll_buffer`.\n That way the user can search through the history and copy/paste.\n '
self.terminal.enter_copy_mode()
|
def enter_copy_mode(self):
'\n Suspend the process, and copy the screen content to the `scroll_buffer`.\n That way the user can search through the history and copy/paste.\n '
self.terminal.enter_copy_mode()<|docstring|>Suspend the process, and copy the screen content to the `scroll_buffer`.
That way the user can search through the history and copy/paste.<|endoftext|>
|
e72d6844c60c2d388863a5e7f24b278b8d3c4fa35eee80b366cb3d17a2f2be24
|
def focus(self):
'\n Focus this pane.\n '
get_app().layout.focus(self.terminal)
|
Focus this pane.
|
pymux/arrangement.py
|
focus
|
deepakbhilare/pymux
| 1,280 |
python
|
def focus(self):
'\n \n '
get_app().layout.focus(self.terminal)
|
def focus(self):
'\n \n '
get_app().layout.focus(self.terminal)<|docstring|>Focus this pane.<|endoftext|>
|
6bb626aeb4c8005d10480edb72eba0f1d66525e3385b857eae1cd3705460eb20
|
def invalidation_hash(self):
'\n Return a hash (string) that can be used to determine when the layout\n has to be rebuild.\n '
def _hash_for_split(split):
result = []
for item in split:
if isinstance(item, (VSplit, HSplit)):
result.append(_hash_for_split(item))
elif isinstance(item, Pane):
result.append(('p%s' % item.pane_id))
if isinstance(split, HSplit):
return ('HSplit(%s)' % ','.join(result))
else:
return ('VSplit(%s)' % ','.join(result))
return ('<window_id=%s,zoom=%s,children=%s>' % (self.window_id, self.zoom, _hash_for_split(self.root)))
|
Return a hash (string) that can be used to determine when the layout
has to be rebuild.
|
pymux/arrangement.py
|
invalidation_hash
|
deepakbhilare/pymux
| 1,280 |
python
|
def invalidation_hash(self):
'\n Return a hash (string) that can be used to determine when the layout\n has to be rebuild.\n '
def _hash_for_split(split):
result = []
for item in split:
if isinstance(item, (VSplit, HSplit)):
result.append(_hash_for_split(item))
elif isinstance(item, Pane):
result.append(('p%s' % item.pane_id))
if isinstance(split, HSplit):
return ('HSplit(%s)' % ','.join(result))
else:
return ('VSplit(%s)' % ','.join(result))
return ('<window_id=%s,zoom=%s,children=%s>' % (self.window_id, self.zoom, _hash_for_split(self.root)))
|
def invalidation_hash(self):
'\n Return a hash (string) that can be used to determine when the layout\n has to be rebuild.\n '
def _hash_for_split(split):
result = []
for item in split:
if isinstance(item, (VSplit, HSplit)):
result.append(_hash_for_split(item))
elif isinstance(item, Pane):
result.append(('p%s' % item.pane_id))
if isinstance(split, HSplit):
return ('HSplit(%s)' % ','.join(result))
else:
return ('VSplit(%s)' % ','.join(result))
return ('<window_id=%s,zoom=%s,children=%s>' % (self.window_id, self.zoom, _hash_for_split(self.root)))<|docstring|>Return a hash (string) that can be used to determine when the layout
has to be rebuild.<|endoftext|>
|
1a2d598b5cd3b74ad9f0e18914d759dbe5b7c76350b3ce8a6b3159a4489b435e
|
@property
def active_pane(self):
'\n The current active :class:`.Pane`.\n '
return self._active_pane
|
The current active :class:`.Pane`.
|
pymux/arrangement.py
|
active_pane
|
deepakbhilare/pymux
| 1,280 |
python
|
@property
def active_pane(self):
'\n \n '
return self._active_pane
|
@property
def active_pane(self):
'\n \n '
return self._active_pane<|docstring|>The current active :class:`.Pane`.<|endoftext|>
|
aab554e34774c9ce7352cab75b9bbe0dc0bd2ff0fcde1da6f3f451dc282bb86c
|
@property
def previous_active_pane(self):
'\n The previous active :class:`.Pane` or `None` if unknown.\n '
p = (self._prev_active_pane and self._prev_active_pane())
if (p and (p in self.panes)):
return p
|
The previous active :class:`.Pane` or `None` if unknown.
|
pymux/arrangement.py
|
previous_active_pane
|
deepakbhilare/pymux
| 1,280 |
python
|
@property
def previous_active_pane(self):
'\n \n '
p = (self._prev_active_pane and self._prev_active_pane())
if (p and (p in self.panes)):
return p
|
@property
def previous_active_pane(self):
'\n \n '
p = (self._prev_active_pane and self._prev_active_pane())
if (p and (p in self.panes)):
return p<|docstring|>The previous active :class:`.Pane` or `None` if unknown.<|endoftext|>
|
0eb4ae56b2913c1b747387441b2b9d91eb38bacda25c941e57da8b6438134335
|
@property
def name(self):
'\n The name for this window as it should be displayed in the status bar.\n '
if self.chosen_name:
return self.chosen_name
else:
pane = self.active_pane
if pane:
return pane.name
return ''
|
The name for this window as it should be displayed in the status bar.
|
pymux/arrangement.py
|
name
|
deepakbhilare/pymux
| 1,280 |
python
|
@property
def name(self):
'\n \n '
if self.chosen_name:
return self.chosen_name
else:
pane = self.active_pane
if pane:
return pane.name
return
|
@property
def name(self):
'\n \n '
if self.chosen_name:
return self.chosen_name
else:
pane = self.active_pane
if pane:
return pane.name
return <|docstring|>The name for this window as it should be displayed in the status bar.<|endoftext|>
|
e87b3b95715b113967bf0e9f5a503b37e04a2b49e36277bf08112baaeb5b1f83
|
def add_pane(self, pane, vsplit=False):
'\n Add another pane to this Window.\n '
assert isinstance(pane, Pane)
assert isinstance(vsplit, bool)
split_cls = (VSplit if vsplit else HSplit)
if (self.active_pane is None):
self.root.append(pane)
else:
parent = self._get_parent(self.active_pane)
same_direction = isinstance(parent, split_cls)
index = parent.index(self.active_pane)
if same_direction:
parent.insert((index + 1), pane)
else:
new_split = split_cls([self.active_pane, pane])
parent[index] = new_split
parent.weights[new_split] = parent.weights[self.active_pane]
self.active_pane = pane
self.zoom = False
|
Add another pane to this Window.
|
pymux/arrangement.py
|
add_pane
|
deepakbhilare/pymux
| 1,280 |
python
|
def add_pane(self, pane, vsplit=False):
'\n \n '
assert isinstance(pane, Pane)
assert isinstance(vsplit, bool)
split_cls = (VSplit if vsplit else HSplit)
if (self.active_pane is None):
self.root.append(pane)
else:
parent = self._get_parent(self.active_pane)
same_direction = isinstance(parent, split_cls)
index = parent.index(self.active_pane)
if same_direction:
parent.insert((index + 1), pane)
else:
new_split = split_cls([self.active_pane, pane])
parent[index] = new_split
parent.weights[new_split] = parent.weights[self.active_pane]
self.active_pane = pane
self.zoom = False
|
def add_pane(self, pane, vsplit=False):
'\n \n '
assert isinstance(pane, Pane)
assert isinstance(vsplit, bool)
split_cls = (VSplit if vsplit else HSplit)
if (self.active_pane is None):
self.root.append(pane)
else:
parent = self._get_parent(self.active_pane)
same_direction = isinstance(parent, split_cls)
index = parent.index(self.active_pane)
if same_direction:
parent.insert((index + 1), pane)
else:
new_split = split_cls([self.active_pane, pane])
parent[index] = new_split
parent.weights[new_split] = parent.weights[self.active_pane]
self.active_pane = pane
self.zoom = False<|docstring|>Add another pane to this Window.<|endoftext|>
|
eaf3d536f94825ac77db4fd45122c75fdb548732df6a434f6392c5a48457634b
|
def remove_pane(self, pane):
'\n Remove pane from this Window.\n '
assert isinstance(pane, Pane)
if (pane in self.panes):
if (pane == self.active_pane):
if self.previous_active_pane:
self.active_pane = self.previous_active_pane
else:
self.focus_next()
p = self._get_parent(pane)
p.remove(pane)
while ((len(p) == 0) and (p != self.root)):
p2 = self._get_parent(p)
p2.remove(p)
p = p2
while ((len(p) == 1) and (p != self.root)):
p2 = self._get_parent(p)
p2.weights[p[0]] = p2.weights[p]
i = p2.index(p)
p2[i] = p[0]
p = p2
|
Remove pane from this Window.
|
pymux/arrangement.py
|
remove_pane
|
deepakbhilare/pymux
| 1,280 |
python
|
def remove_pane(self, pane):
'\n \n '
assert isinstance(pane, Pane)
if (pane in self.panes):
if (pane == self.active_pane):
if self.previous_active_pane:
self.active_pane = self.previous_active_pane
else:
self.focus_next()
p = self._get_parent(pane)
p.remove(pane)
while ((len(p) == 0) and (p != self.root)):
p2 = self._get_parent(p)
p2.remove(p)
p = p2
while ((len(p) == 1) and (p != self.root)):
p2 = self._get_parent(p)
p2.weights[p[0]] = p2.weights[p]
i = p2.index(p)
p2[i] = p[0]
p = p2
|
def remove_pane(self, pane):
'\n \n '
assert isinstance(pane, Pane)
if (pane in self.panes):
if (pane == self.active_pane):
if self.previous_active_pane:
self.active_pane = self.previous_active_pane
else:
self.focus_next()
p = self._get_parent(pane)
p.remove(pane)
while ((len(p) == 0) and (p != self.root)):
p2 = self._get_parent(p)
p2.remove(p)
p = p2
while ((len(p) == 1) and (p != self.root)):
p2 = self._get_parent(p)
p2.weights[p[0]] = p2.weights[p]
i = p2.index(p)
p2[i] = p[0]
p = p2<|docstring|>Remove pane from this Window.<|endoftext|>
|
377da52eed69e0bf4ce2671ecd7dfe198f373a1b2f5538bed68c1add3865c178
|
@property
def panes(self):
' List with all panes from this Window. '
result = []
for s in self.splits:
for item in s:
if isinstance(item, Pane):
result.append(item)
return result
|
List with all panes from this Window.
|
pymux/arrangement.py
|
panes
|
deepakbhilare/pymux
| 1,280 |
python
|
@property
def panes(self):
' '
result = []
for s in self.splits:
for item in s:
if isinstance(item, Pane):
result.append(item)
return result
|
@property
def panes(self):
' '
result = []
for s in self.splits:
for item in s:
if isinstance(item, Pane):
result.append(item)
return result<|docstring|>List with all panes from this Window.<|endoftext|>
|
20e2d6289afca3fd89bafd4186d067742d6efad7e9c1a3db7b3ab02bf7fd2f8c
|
@property
def splits(self):
' Return a list with all HSplit/VSplit instances. '
result = []
def collect(split):
result.append(split)
for item in split:
if isinstance(item, (HSplit, VSplit)):
collect(item)
collect(self.root)
return result
|
Return a list with all HSplit/VSplit instances.
|
pymux/arrangement.py
|
splits
|
deepakbhilare/pymux
| 1,280 |
python
|
@property
def splits(self):
' '
result = []
def collect(split):
result.append(split)
for item in split:
if isinstance(item, (HSplit, VSplit)):
collect(item)
collect(self.root)
return result
|
@property
def splits(self):
' '
result = []
def collect(split):
result.append(split)
for item in split:
if isinstance(item, (HSplit, VSplit)):
collect(item)
collect(self.root)
return result<|docstring|>Return a list with all HSplit/VSplit instances.<|endoftext|>
|
0b2583cd41464b0c0538be7d52597ff61cf6e2496626f361493665bce58cf30c
|
def _get_parent(self, item):
' The HSplit/VSplit that contains the active pane. '
for s in self.splits:
if (item in s):
return s
|
The HSplit/VSplit that contains the active pane.
|
pymux/arrangement.py
|
_get_parent
|
deepakbhilare/pymux
| 1,280 |
python
|
def _get_parent(self, item):
' '
for s in self.splits:
if (item in s):
return s
|
def _get_parent(self, item):
' '
for s in self.splits:
if (item in s):
return s<|docstring|>The HSplit/VSplit that contains the active pane.<|endoftext|>
|
3613242519442e963cdcf4d5686bcdbbfb278e7502ff132af0f3cfcd102ad564
|
@property
def has_panes(self):
' True when this window contains at least one pane. '
return (len(self.panes) > 0)
|
True when this window contains at least one pane.
|
pymux/arrangement.py
|
has_panes
|
deepakbhilare/pymux
| 1,280 |
python
|
@property
def has_panes(self):
' '
return (len(self.panes) > 0)
|
@property
def has_panes(self):
' '
return (len(self.panes) > 0)<|docstring|>True when this window contains at least one pane.<|endoftext|>
|
d1eda2101bdb3dbae99abeecd09af62d31b75d6fe7dcdef7fcc142b0b65fffeb
|
@property
def active_process(self):
' Return `Process` that should receive user input. '
p = self.active_pane
if (p is not None):
return p.process
|
Return `Process` that should receive user input.
|
pymux/arrangement.py
|
active_process
|
deepakbhilare/pymux
| 1,280 |
python
|
@property
def active_process(self):
' '
p = self.active_pane
if (p is not None):
return p.process
|
@property
def active_process(self):
' '
p = self.active_pane
if (p is not None):
return p.process<|docstring|>Return `Process` that should receive user input.<|endoftext|>
|
35f38e41b7e5aa67daae3adf5a41cf8f7b6f6295322f785876315ac74b519142
|
def focus_next(self, count=1):
' Focus the next pane. '
panes = self.panes
if panes:
self.active_pane = panes[((panes.index(self.active_pane) + count) % len(panes))]
else:
self.active_pane = None
|
Focus the next pane.
|
pymux/arrangement.py
|
focus_next
|
deepakbhilare/pymux
| 1,280 |
python
|
def focus_next(self, count=1):
' '
panes = self.panes
if panes:
self.active_pane = panes[((panes.index(self.active_pane) + count) % len(panes))]
else:
self.active_pane = None
|
def focus_next(self, count=1):
' '
panes = self.panes
if panes:
self.active_pane = panes[((panes.index(self.active_pane) + count) % len(panes))]
else:
self.active_pane = None<|docstring|>Focus the next pane.<|endoftext|>
|
e4ee5340e1f870aa7681630483ec4abd14c4132a894a929c37655670da01f6e7
|
def focus_previous(self):
' Focus the previous pane. '
self.focus_next(count=(- 1))
|
Focus the previous pane.
|
pymux/arrangement.py
|
focus_previous
|
deepakbhilare/pymux
| 1,280 |
python
|
def focus_previous(self):
' '
self.focus_next(count=(- 1))
|
def focus_previous(self):
' '
self.focus_next(count=(- 1))<|docstring|>Focus the previous pane.<|endoftext|>
|
bd242d35596fbb6f88dd7a4d29d6b277b0a60d56a3bf8235b91b87b3fdd08c1e
|
def rotate(self, count=1, with_pane_before_only=False, with_pane_after_only=False):
'\n Rotate panes.\n When `with_pane_before_only` or `with_pane_after_only` is True, only rotate\n with the pane before/after the active pane.\n '
items = []
current_pane_index = None
for s in self.splits:
for (index, item) in enumerate(s):
if isinstance(item, Pane):
items.append((s, index, item, s.weights[item]))
if (item == self.active_pane):
current_pane_index = (len(items) - 1)
if with_pane_before_only:
items = items[(current_pane_index - 1):(current_pane_index + 1)]
elif with_pane_after_only:
items = items[current_pane_index:(current_pane_index + 2)]
for (i, triple) in enumerate(items):
(split, index, pane, weight) = triple
new_item = items[((i + count) % len(items))][2]
split[index] = new_item
split.weights[new_item] = weight
|
Rotate panes.
When `with_pane_before_only` or `with_pane_after_only` is True, only rotate
with the pane before/after the active pane.
|
pymux/arrangement.py
|
rotate
|
deepakbhilare/pymux
| 1,280 |
python
|
def rotate(self, count=1, with_pane_before_only=False, with_pane_after_only=False):
'\n Rotate panes.\n When `with_pane_before_only` or `with_pane_after_only` is True, only rotate\n with the pane before/after the active pane.\n '
items = []
current_pane_index = None
for s in self.splits:
for (index, item) in enumerate(s):
if isinstance(item, Pane):
items.append((s, index, item, s.weights[item]))
if (item == self.active_pane):
current_pane_index = (len(items) - 1)
if with_pane_before_only:
items = items[(current_pane_index - 1):(current_pane_index + 1)]
elif with_pane_after_only:
items = items[current_pane_index:(current_pane_index + 2)]
for (i, triple) in enumerate(items):
(split, index, pane, weight) = triple
new_item = items[((i + count) % len(items))][2]
split[index] = new_item
split.weights[new_item] = weight
|
def rotate(self, count=1, with_pane_before_only=False, with_pane_after_only=False):
'\n Rotate panes.\n When `with_pane_before_only` or `with_pane_after_only` is True, only rotate\n with the pane before/after the active pane.\n '
items = []
current_pane_index = None
for s in self.splits:
for (index, item) in enumerate(s):
if isinstance(item, Pane):
items.append((s, index, item, s.weights[item]))
if (item == self.active_pane):
current_pane_index = (len(items) - 1)
if with_pane_before_only:
items = items[(current_pane_index - 1):(current_pane_index + 1)]
elif with_pane_after_only:
items = items[current_pane_index:(current_pane_index + 2)]
for (i, triple) in enumerate(items):
(split, index, pane, weight) = triple
new_item = items[((i + count) % len(items))][2]
split[index] = new_item
split.weights[new_item] = weight<|docstring|>Rotate panes.
When `with_pane_before_only` or `with_pane_after_only` is True, only rotate
with the pane before/after the active pane.<|endoftext|>
|
5ea7dc7b6898fb8662d02f19594367470095a601d1fe3ae23d0a0079c7523009
|
def select_layout(self, layout_type):
'\n Select one of the predefined layouts.\n '
assert (layout_type in LayoutTypes._ALL)
if (len(self.panes) == 1):
layout_type = LayoutTypes.EVEN_HORIZONTAL
if (layout_type == LayoutTypes.EVEN_HORIZONTAL):
self.root = HSplit(self.panes)
elif (layout_type == LayoutTypes.EVEN_VERTICAL):
self.root = VSplit(self.panes)
elif (layout_type == LayoutTypes.MAIN_HORIZONTAL):
self.root = HSplit([self.active_pane, VSplit([p for p in self.panes if (p != self.active_pane)])])
elif (layout_type == LayoutTypes.MAIN_VERTICAL):
self.root = VSplit([self.active_pane, HSplit([p for p in self.panes if (p != self.active_pane)])])
elif (layout_type == LayoutTypes.TILED):
panes = self.panes
column_count = math.ceil((len(panes) ** 0.5))
rows = HSplit()
current_row = VSplit()
for p in panes:
current_row.append(p)
if (len(current_row) >= column_count):
rows.append(current_row)
current_row = VSplit()
if current_row:
rows.append(current_row)
self.root = rows
self.previous_selected_layout = layout_type
|
Select one of the predefined layouts.
|
pymux/arrangement.py
|
select_layout
|
deepakbhilare/pymux
| 1,280 |
python
|
def select_layout(self, layout_type):
'\n \n '
assert (layout_type in LayoutTypes._ALL)
if (len(self.panes) == 1):
layout_type = LayoutTypes.EVEN_HORIZONTAL
if (layout_type == LayoutTypes.EVEN_HORIZONTAL):
self.root = HSplit(self.panes)
elif (layout_type == LayoutTypes.EVEN_VERTICAL):
self.root = VSplit(self.panes)
elif (layout_type == LayoutTypes.MAIN_HORIZONTAL):
self.root = HSplit([self.active_pane, VSplit([p for p in self.panes if (p != self.active_pane)])])
elif (layout_type == LayoutTypes.MAIN_VERTICAL):
self.root = VSplit([self.active_pane, HSplit([p for p in self.panes if (p != self.active_pane)])])
elif (layout_type == LayoutTypes.TILED):
panes = self.panes
column_count = math.ceil((len(panes) ** 0.5))
rows = HSplit()
current_row = VSplit()
for p in panes:
current_row.append(p)
if (len(current_row) >= column_count):
rows.append(current_row)
current_row = VSplit()
if current_row:
rows.append(current_row)
self.root = rows
self.previous_selected_layout = layout_type
|
def select_layout(self, layout_type):
'\n \n '
assert (layout_type in LayoutTypes._ALL)
if (len(self.panes) == 1):
layout_type = LayoutTypes.EVEN_HORIZONTAL
if (layout_type == LayoutTypes.EVEN_HORIZONTAL):
self.root = HSplit(self.panes)
elif (layout_type == LayoutTypes.EVEN_VERTICAL):
self.root = VSplit(self.panes)
elif (layout_type == LayoutTypes.MAIN_HORIZONTAL):
self.root = HSplit([self.active_pane, VSplit([p for p in self.panes if (p != self.active_pane)])])
elif (layout_type == LayoutTypes.MAIN_VERTICAL):
self.root = VSplit([self.active_pane, HSplit([p for p in self.panes if (p != self.active_pane)])])
elif (layout_type == LayoutTypes.TILED):
panes = self.panes
column_count = math.ceil((len(panes) ** 0.5))
rows = HSplit()
current_row = VSplit()
for p in panes:
current_row.append(p)
if (len(current_row) >= column_count):
rows.append(current_row)
current_row = VSplit()
if current_row:
rows.append(current_row)
self.root = rows
self.previous_selected_layout = layout_type<|docstring|>Select one of the predefined layouts.<|endoftext|>
|
75493531cec7e69c7d3595f52f7480185b7357e5c312b98ef7aea1f439534e58
|
def select_next_layout(self, count=1):
'\n Select next layout. (Cycle through predefined layouts.)\n '
if (len(self.panes) == 2):
all_layouts = [LayoutTypes.EVEN_HORIZONTAL, LayoutTypes.EVEN_VERTICAL]
else:
all_layouts = LayoutTypes._ALL
layout = (self.previous_selected_layout or LayoutTypes._ALL[(- 1)])
try:
index = all_layouts.index(layout)
except ValueError:
index = 0
new_layout = all_layouts[((index + count) % len(all_layouts))]
self.select_layout(new_layout)
|
Select next layout. (Cycle through predefined layouts.)
|
pymux/arrangement.py
|
select_next_layout
|
deepakbhilare/pymux
| 1,280 |
python
|
def select_next_layout(self, count=1):
'\n \n '
if (len(self.panes) == 2):
all_layouts = [LayoutTypes.EVEN_HORIZONTAL, LayoutTypes.EVEN_VERTICAL]
else:
all_layouts = LayoutTypes._ALL
layout = (self.previous_selected_layout or LayoutTypes._ALL[(- 1)])
try:
index = all_layouts.index(layout)
except ValueError:
index = 0
new_layout = all_layouts[((index + count) % len(all_layouts))]
self.select_layout(new_layout)
|
def select_next_layout(self, count=1):
'\n \n '
if (len(self.panes) == 2):
all_layouts = [LayoutTypes.EVEN_HORIZONTAL, LayoutTypes.EVEN_VERTICAL]
else:
all_layouts = LayoutTypes._ALL
layout = (self.previous_selected_layout or LayoutTypes._ALL[(- 1)])
try:
index = all_layouts.index(layout)
except ValueError:
index = 0
new_layout = all_layouts[((index + count) % len(all_layouts))]
self.select_layout(new_layout)<|docstring|>Select next layout. (Cycle through predefined layouts.)<|endoftext|>
|
8fd4a4e8cdb1f9827b9618e7faac3a9a3b67a4ca466a84ba4d57d0c6f90a5e39
|
def change_size_for_active_pane(self, up=0, right=0, down=0, left=0):
'\n Increase the size of the current pane in any of the four directions.\n '
child = self.active_pane
self.change_size_for_pane(child, up=up, right=right, down=down, left=left)
|
Increase the size of the current pane in any of the four directions.
|
pymux/arrangement.py
|
change_size_for_active_pane
|
deepakbhilare/pymux
| 1,280 |
python
|
def change_size_for_active_pane(self, up=0, right=0, down=0, left=0):
'\n \n '
child = self.active_pane
self.change_size_for_pane(child, up=up, right=right, down=down, left=left)
|
def change_size_for_active_pane(self, up=0, right=0, down=0, left=0):
'\n \n '
child = self.active_pane
self.change_size_for_pane(child, up=up, right=right, down=down, left=left)<|docstring|>Increase the size of the current pane in any of the four directions.<|endoftext|>
|
1552c45ad47d3f89113360e09a46e551c26810be8d7d145856f9e91478d3f065
|
def change_size_for_pane(self, pane, up=0, right=0, down=0, left=0):
'\n Increase the size of the current pane in any of the four directions.\n Positive values indicate an increase, negative values a decrease.\n '
assert isinstance(pane, Pane)
def find_split_and_child(split_cls, is_before):
' Find the split for which we will have to update the weights. '
child = pane
split = self._get_parent(child)
def found():
return (isinstance(split, split_cls) and ((not is_before) or (split.index(child) > 0)) and (is_before or (split.index(child) < (len(split) - 1))))
while (split and (not found())):
child = split
split = self._get_parent(child)
return (split, child)
def handle_side(split_cls, is_before, amount, trying_other_side=False):
' Increase weights on one side. (top/left/right/bottom). '
if amount:
(split, child) = find_split_and_child(split_cls, is_before)
if split:
neighbour_index = (split.index(child) + ((- 1) if is_before else 1))
neighbour_child = split[neighbour_index]
split.weights[child] += amount
split.weights[neighbour_child] -= amount
for (k, value) in split.weights.items():
if (value < 1):
split.weights[k] = 1
elif (not trying_other_side):
handle_side(split_cls, (not is_before), (- amount), trying_other_side=True)
handle_side(VSplit, True, left)
handle_side(VSplit, False, right)
handle_side(HSplit, True, up)
handle_side(HSplit, False, down)
|
Increase the size of the current pane in any of the four directions.
Positive values indicate an increase, negative values a decrease.
|
pymux/arrangement.py
|
change_size_for_pane
|
deepakbhilare/pymux
| 1,280 |
python
|
def change_size_for_pane(self, pane, up=0, right=0, down=0, left=0):
'\n Increase the size of the current pane in any of the four directions.\n Positive values indicate an increase, negative values a decrease.\n '
assert isinstance(pane, Pane)
def find_split_and_child(split_cls, is_before):
' Find the split for which we will have to update the weights. '
child = pane
split = self._get_parent(child)
def found():
return (isinstance(split, split_cls) and ((not is_before) or (split.index(child) > 0)) and (is_before or (split.index(child) < (len(split) - 1))))
while (split and (not found())):
child = split
split = self._get_parent(child)
return (split, child)
def handle_side(split_cls, is_before, amount, trying_other_side=False):
' Increase weights on one side. (top/left/right/bottom). '
if amount:
(split, child) = find_split_and_child(split_cls, is_before)
if split:
neighbour_index = (split.index(child) + ((- 1) if is_before else 1))
neighbour_child = split[neighbour_index]
split.weights[child] += amount
split.weights[neighbour_child] -= amount
for (k, value) in split.weights.items():
if (value < 1):
split.weights[k] = 1
elif (not trying_other_side):
handle_side(split_cls, (not is_before), (- amount), trying_other_side=True)
handle_side(VSplit, True, left)
handle_side(VSplit, False, right)
handle_side(HSplit, True, up)
handle_side(HSplit, False, down)
|
def change_size_for_pane(self, pane, up=0, right=0, down=0, left=0):
'\n Increase the size of the current pane in any of the four directions.\n Positive values indicate an increase, negative values a decrease.\n '
assert isinstance(pane, Pane)
def find_split_and_child(split_cls, is_before):
' Find the split for which we will have to update the weights. '
child = pane
split = self._get_parent(child)
def found():
return (isinstance(split, split_cls) and ((not is_before) or (split.index(child) > 0)) and (is_before or (split.index(child) < (len(split) - 1))))
while (split and (not found())):
child = split
split = self._get_parent(child)
return (split, child)
def handle_side(split_cls, is_before, amount, trying_other_side=False):
' Increase weights on one side. (top/left/right/bottom). '
if amount:
(split, child) = find_split_and_child(split_cls, is_before)
if split:
neighbour_index = (split.index(child) + ((- 1) if is_before else 1))
neighbour_child = split[neighbour_index]
split.weights[child] += amount
split.weights[neighbour_child] -= amount
for (k, value) in split.weights.items():
if (value < 1):
split.weights[k] = 1
elif (not trying_other_side):
handle_side(split_cls, (not is_before), (- amount), trying_other_side=True)
handle_side(VSplit, True, left)
handle_side(VSplit, False, right)
handle_side(HSplit, True, up)
handle_side(HSplit, False, down)<|docstring|>Increase the size of the current pane in any of the four directions.
Positive values indicate an increase, negative values a decrease.<|endoftext|>
|
8869bb5e10e7e5efde04e91c6ad516f6b50d03ce5b9bffd3cab6190e4e0eda21
|
def get_pane_index(self, pane):
' Return the index of the given pane. ValueError if not found. '
assert isinstance(pane, Pane)
return self.panes.index(pane)
|
Return the index of the given pane. ValueError if not found.
|
pymux/arrangement.py
|
get_pane_index
|
deepakbhilare/pymux
| 1,280 |
python
|
def get_pane_index(self, pane):
' '
assert isinstance(pane, Pane)
return self.panes.index(pane)
|
def get_pane_index(self, pane):
' '
assert isinstance(pane, Pane)
return self.panes.index(pane)<|docstring|>Return the index of the given pane. ValueError if not found.<|endoftext|>
|
22f65a359dd1fdaa23f2776fcd2d762681f1be547e3df5f521041982c477d0bb
|
def invalidation_hash(self):
'\n When this changes, the layout needs to be rebuild.\n '
if (not self.windows):
return '<no-windows>'
w = self.get_active_window()
return w.invalidation_hash()
|
When this changes, the layout needs to be rebuild.
|
pymux/arrangement.py
|
invalidation_hash
|
deepakbhilare/pymux
| 1,280 |
python
|
def invalidation_hash(self):
'\n \n '
if (not self.windows):
return '<no-windows>'
w = self.get_active_window()
return w.invalidation_hash()
|
def invalidation_hash(self):
'\n \n '
if (not self.windows):
return '<no-windows>'
w = self.get_active_window()
return w.invalidation_hash()<|docstring|>When this changes, the layout needs to be rebuild.<|endoftext|>
|
76d13b4588b74b10847a3a29f01c6577d81ae581adebeee7cc0bbb9d8e9992c6
|
def get_active_window(self):
'\n The current active :class:`.Window`.\n '
app = get_app()
try:
return self._active_window_for_cli[app]
except KeyError:
self._active_window_for_cli[app] = (self._last_active_window or self.windows[0])
return self.windows[0]
|
The current active :class:`.Window`.
|
pymux/arrangement.py
|
get_active_window
|
deepakbhilare/pymux
| 1,280 |
python
|
def get_active_window(self):
'\n \n '
app = get_app()
try:
return self._active_window_for_cli[app]
except KeyError:
self._active_window_for_cli[app] = (self._last_active_window or self.windows[0])
return self.windows[0]
|
def get_active_window(self):
'\n \n '
app = get_app()
try:
return self._active_window_for_cli[app]
except KeyError:
self._active_window_for_cli[app] = (self._last_active_window or self.windows[0])
return self.windows[0]<|docstring|>The current active :class:`.Window`.<|endoftext|>
|
c3bda564113120da0593bd6f1e2708595f485758208c323952db07f02753a7c9
|
def set_active_window_from_pane_id(self, pane_id):
'\n Make the window with this pane ID the active Window.\n '
assert isinstance(pane_id, int)
for w in self.windows:
for p in w.panes:
if (p.pane_id == pane_id):
self.set_active_window(w)
|
Make the window with this pane ID the active Window.
|
pymux/arrangement.py
|
set_active_window_from_pane_id
|
deepakbhilare/pymux
| 1,280 |
python
|
def set_active_window_from_pane_id(self, pane_id):
'\n \n '
assert isinstance(pane_id, int)
for w in self.windows:
for p in w.panes:
if (p.pane_id == pane_id):
self.set_active_window(w)
|
def set_active_window_from_pane_id(self, pane_id):
'\n \n '
assert isinstance(pane_id, int)
for w in self.windows:
for p in w.panes:
if (p.pane_id == pane_id):
self.set_active_window(w)<|docstring|>Make the window with this pane ID the active Window.<|endoftext|>
|
5071e04957205c25aa8119a6ada52ded48a9bc1147f398cfeef03f4f2077adee
|
def get_previous_active_window(self):
' The previous active Window or None if unknown. '
app = get_app()
try:
return self._prev_active_window_for_cli[app]
except KeyError:
return None
|
The previous active Window or None if unknown.
|
pymux/arrangement.py
|
get_previous_active_window
|
deepakbhilare/pymux
| 1,280 |
python
|
def get_previous_active_window(self):
' '
app = get_app()
try:
return self._prev_active_window_for_cli[app]
except KeyError:
return None
|
def get_previous_active_window(self):
' '
app = get_app()
try:
return self._prev_active_window_for_cli[app]
except KeyError:
return None<|docstring|>The previous active Window or None if unknown.<|endoftext|>
|
cd0da9057fe6b57a1454275e262f733c6bb44a6a30ba061e56438f89ac969799
|
def get_window_by_index(self, index):
' Return the Window with this index or None if not found. '
for w in self.windows:
if (w.index == index):
return w
|
Return the Window with this index or None if not found.
|
pymux/arrangement.py
|
get_window_by_index
|
deepakbhilare/pymux
| 1,280 |
python
|
def get_window_by_index(self, index):
' '
for w in self.windows:
if (w.index == index):
return w
|
def get_window_by_index(self, index):
' '
for w in self.windows:
if (w.index == index):
return w<|docstring|>Return the Window with this index or None if not found.<|endoftext|>
|
cee7b9682c6108332439c2d60cacb9eaa4044ced1977e678122b8764b96b344c
|
def create_window(self, pane, name=None, set_active=True):
'\n Create a new window that contains just this pane.\n\n :param pane: The :class:`.Pane` instance to put in the new window.\n :param name: If given, name for the new window.\n :param set_active: When True, focus the new window.\n '
assert isinstance(pane, Pane)
assert ((name is None) or isinstance(name, six.text_type))
taken_indexes = [w.index for w in self.windows]
index = self.base_index
while (index in taken_indexes):
index += 1
w = Window(index)
w.add_pane(pane)
self.windows.append(w)
self.windows = sorted(self.windows, key=(lambda w: w.index))
app = get_app(return_none=True)
if ((app is not None) and set_active):
self.set_active_window(w)
if (name is not None):
w.chosen_name = name
assert (w.active_pane == pane)
assert w._get_parent(pane)
|
Create a new window that contains just this pane.
:param pane: The :class:`.Pane` instance to put in the new window.
:param name: If given, name for the new window.
:param set_active: When True, focus the new window.
|
pymux/arrangement.py
|
create_window
|
deepakbhilare/pymux
| 1,280 |
python
|
def create_window(self, pane, name=None, set_active=True):
'\n Create a new window that contains just this pane.\n\n :param pane: The :class:`.Pane` instance to put in the new window.\n :param name: If given, name for the new window.\n :param set_active: When True, focus the new window.\n '
assert isinstance(pane, Pane)
assert ((name is None) or isinstance(name, six.text_type))
taken_indexes = [w.index for w in self.windows]
index = self.base_index
while (index in taken_indexes):
index += 1
w = Window(index)
w.add_pane(pane)
self.windows.append(w)
self.windows = sorted(self.windows, key=(lambda w: w.index))
app = get_app(return_none=True)
if ((app is not None) and set_active):
self.set_active_window(w)
if (name is not None):
w.chosen_name = name
assert (w.active_pane == pane)
assert w._get_parent(pane)
|
def create_window(self, pane, name=None, set_active=True):
'\n Create a new window that contains just this pane.\n\n :param pane: The :class:`.Pane` instance to put in the new window.\n :param name: If given, name for the new window.\n :param set_active: When True, focus the new window.\n '
assert isinstance(pane, Pane)
assert ((name is None) or isinstance(name, six.text_type))
taken_indexes = [w.index for w in self.windows]
index = self.base_index
while (index in taken_indexes):
index += 1
w = Window(index)
w.add_pane(pane)
self.windows.append(w)
self.windows = sorted(self.windows, key=(lambda w: w.index))
app = get_app(return_none=True)
if ((app is not None) and set_active):
self.set_active_window(w)
if (name is not None):
w.chosen_name = name
assert (w.active_pane == pane)
assert w._get_parent(pane)<|docstring|>Create a new window that contains just this pane.
:param pane: The :class:`.Pane` instance to put in the new window.
:param name: If given, name for the new window.
:param set_active: When True, focus the new window.<|endoftext|>
|
b19db99b6c458b9901efa317cce1553718b2ecf1a1fb67f05807f0d2f3716680
|
def move_window(self, window, new_index):
'\n Move window to a new index.\n '
assert isinstance(window, Window)
assert isinstance(new_index, int)
window.index = new_index
self.windows = sorted(self.windows, key=(lambda w: w.index))
|
Move window to a new index.
|
pymux/arrangement.py
|
move_window
|
deepakbhilare/pymux
| 1,280 |
python
|
def move_window(self, window, new_index):
'\n \n '
assert isinstance(window, Window)
assert isinstance(new_index, int)
window.index = new_index
self.windows = sorted(self.windows, key=(lambda w: w.index))
|
def move_window(self, window, new_index):
'\n \n '
assert isinstance(window, Window)
assert isinstance(new_index, int)
window.index = new_index
self.windows = sorted(self.windows, key=(lambda w: w.index))<|docstring|>Move window to a new index.<|endoftext|>
|
ab310665cc390422bdf2a22aba5893d605f55c9249f484a96f474a1d71bd0836
|
def get_active_pane(self):
'\n The current :class:`.Pane` from the current window.\n '
w = self.get_active_window()
if (w is not None):
return w.active_pane
|
The current :class:`.Pane` from the current window.
|
pymux/arrangement.py
|
get_active_pane
|
deepakbhilare/pymux
| 1,280 |
python
|
def get_active_pane(self):
'\n \n '
w = self.get_active_window()
if (w is not None):
return w.active_pane
|
def get_active_pane(self):
'\n \n '
w = self.get_active_window()
if (w is not None):
return w.active_pane<|docstring|>The current :class:`.Pane` from the current window.<|endoftext|>
|
efd4d1835a60e27e3abf1af0a1891fa94655f38ddebbeb4ee31b145079ca31a8
|
def remove_pane(self, pane):
'\n Remove a :class:`.Pane`. (Look in all windows.)\n '
assert isinstance(pane, Pane)
for w in self.windows:
w.remove_pane(pane)
if (not w.has_panes):
for (app, active_w) in self._active_window_for_cli.items():
if (w == active_w):
with set_app(app):
self.focus_next_window()
self.windows.remove(w)
|
Remove a :class:`.Pane`. (Look in all windows.)
|
pymux/arrangement.py
|
remove_pane
|
deepakbhilare/pymux
| 1,280 |
python
|
def remove_pane(self, pane):
'\n \n '
assert isinstance(pane, Pane)
for w in self.windows:
w.remove_pane(pane)
if (not w.has_panes):
for (app, active_w) in self._active_window_for_cli.items():
if (w == active_w):
with set_app(app):
self.focus_next_window()
self.windows.remove(w)
|
def remove_pane(self, pane):
'\n \n '
assert isinstance(pane, Pane)
for w in self.windows:
w.remove_pane(pane)
if (not w.has_panes):
for (app, active_w) in self._active_window_for_cli.items():
if (w == active_w):
with set_app(app):
self.focus_next_window()
self.windows.remove(w)<|docstring|>Remove a :class:`.Pane`. (Look in all windows.)<|endoftext|>
|
ebce2d42288c473d4cbc146a242a848ddb66488fb133c88e22cd8a90af3ee681
|
def break_pane(self, set_active=True):
'\n When the current window has multiple panes, remove the pane from this\n window and put it in a new window.\n\n :param set_active: When True, focus the new window.\n '
w = self.get_active_window()
if (len(w.panes) > 1):
pane = w.active_pane
self.get_active_window().remove_pane(pane)
self.create_window(pane, set_active=set_active)
|
When the current window has multiple panes, remove the pane from this
window and put it in a new window.
:param set_active: When True, focus the new window.
|
pymux/arrangement.py
|
break_pane
|
deepakbhilare/pymux
| 1,280 |
python
|
def break_pane(self, set_active=True):
'\n When the current window has multiple panes, remove the pane from this\n window and put it in a new window.\n\n :param set_active: When True, focus the new window.\n '
w = self.get_active_window()
if (len(w.panes) > 1):
pane = w.active_pane
self.get_active_window().remove_pane(pane)
self.create_window(pane, set_active=set_active)
|
def break_pane(self, set_active=True):
'\n When the current window has multiple panes, remove the pane from this\n window and put it in a new window.\n\n :param set_active: When True, focus the new window.\n '
w = self.get_active_window()
if (len(w.panes) > 1):
pane = w.active_pane
self.get_active_window().remove_pane(pane)
self.create_window(pane, set_active=set_active)<|docstring|>When the current window has multiple panes, remove the pane from this
window and put it in a new window.
:param set_active: When True, focus the new window.<|endoftext|>
|
8a30dd450119a5db51a845cb8d238e6675dfd87018394426947d5bdf422d1d36
|
def rotate_window(self, count=1):
' Rotate the panes in the active window. '
w = self.get_active_window()
w.rotate(count=count)
|
Rotate the panes in the active window.
|
pymux/arrangement.py
|
rotate_window
|
deepakbhilare/pymux
| 1,280 |
python
|
def rotate_window(self, count=1):
' '
w = self.get_active_window()
w.rotate(count=count)
|
def rotate_window(self, count=1):
' '
w = self.get_active_window()
w.rotate(count=count)<|docstring|>Rotate the panes in the active window.<|endoftext|>
|
addf7187351c2b904001eb9c0a4a15db9db4105039bfe236c551ccf395e347b8
|
@property
def has_panes(self):
' True when any of the windows has a :class:`.Pane`. '
for w in self.windows:
if w.has_panes:
return True
return False
|
True when any of the windows has a :class:`.Pane`.
|
pymux/arrangement.py
|
has_panes
|
deepakbhilare/pymux
| 1,280 |
python
|
@property
def has_panes(self):
' '
for w in self.windows:
if w.has_panes:
return True
return False
|
@property
def has_panes(self):
' '
for w in self.windows:
if w.has_panes:
return True
return False<|docstring|>True when any of the windows has a :class:`.Pane`.<|endoftext|>
|
46f1b1011769d32ec714d211c3aa9efc4870bb9301666c245688659c64741acb
|
def find_split_and_child(split_cls, is_before):
' Find the split for which we will have to update the weights. '
child = pane
split = self._get_parent(child)
def found():
return (isinstance(split, split_cls) and ((not is_before) or (split.index(child) > 0)) and (is_before or (split.index(child) < (len(split) - 1))))
while (split and (not found())):
child = split
split = self._get_parent(child)
return (split, child)
|
Find the split for which we will have to update the weights.
|
pymux/arrangement.py
|
find_split_and_child
|
deepakbhilare/pymux
| 1,280 |
python
|
def find_split_and_child(split_cls, is_before):
' '
child = pane
split = self._get_parent(child)
def found():
return (isinstance(split, split_cls) and ((not is_before) or (split.index(child) > 0)) and (is_before or (split.index(child) < (len(split) - 1))))
while (split and (not found())):
child = split
split = self._get_parent(child)
return (split, child)
|
def find_split_and_child(split_cls, is_before):
' '
child = pane
split = self._get_parent(child)
def found():
return (isinstance(split, split_cls) and ((not is_before) or (split.index(child) > 0)) and (is_before or (split.index(child) < (len(split) - 1))))
while (split and (not found())):
child = split
split = self._get_parent(child)
return (split, child)<|docstring|>Find the split for which we will have to update the weights.<|endoftext|>
|
7f888aca53e6bb57730b5cc82a991acee4636defd897e5d8d68cdc87e21d88d4
|
def handle_side(split_cls, is_before, amount, trying_other_side=False):
' Increase weights on one side. (top/left/right/bottom). '
if amount:
(split, child) = find_split_and_child(split_cls, is_before)
if split:
neighbour_index = (split.index(child) + ((- 1) if is_before else 1))
neighbour_child = split[neighbour_index]
split.weights[child] += amount
split.weights[neighbour_child] -= amount
for (k, value) in split.weights.items():
if (value < 1):
split.weights[k] = 1
elif (not trying_other_side):
handle_side(split_cls, (not is_before), (- amount), trying_other_side=True)
|
Increase weights on one side. (top/left/right/bottom).
|
pymux/arrangement.py
|
handle_side
|
deepakbhilare/pymux
| 1,280 |
python
|
def handle_side(split_cls, is_before, amount, trying_other_side=False):
' '
if amount:
(split, child) = find_split_and_child(split_cls, is_before)
if split:
neighbour_index = (split.index(child) + ((- 1) if is_before else 1))
neighbour_child = split[neighbour_index]
split.weights[child] += amount
split.weights[neighbour_child] -= amount
for (k, value) in split.weights.items():
if (value < 1):
split.weights[k] = 1
elif (not trying_other_side):
handle_side(split_cls, (not is_before), (- amount), trying_other_side=True)
|
def handle_side(split_cls, is_before, amount, trying_other_side=False):
' '
if amount:
(split, child) = find_split_and_child(split_cls, is_before)
if split:
neighbour_index = (split.index(child) + ((- 1) if is_before else 1))
neighbour_child = split[neighbour_index]
split.weights[child] += amount
split.weights[neighbour_child] -= amount
for (k, value) in split.weights.items():
if (value < 1):
split.weights[k] = 1
elif (not trying_other_side):
handle_side(split_cls, (not is_before), (- amount), trying_other_side=True)<|docstring|>Increase weights on one side. (top/left/right/bottom).<|endoftext|>
|
983314e8b950b0ff7f61fc1f578500f03c82427fdcc423a6d370fde03b0720bf
|
def parse_node(tag, attrib):
"Parse individual XML node of tenhou mjlog.\n\n Parameters\n ----------\n tag : str\n Tags such as 'GO', 'DORA', 'AGARI' etc...\n\n attrib: dict or list\n Attribute of the node\n\n Returns\n -------\n dict\n JSON object\n "
attrib = _ensure_unicode(attrib)
_LG.debug('Input: %s: %s', tag, attrib)
if (tag == 'GO'):
data = _parse_go(attrib)
elif (tag == 'UN'):
if (len(attrib) == 1):
data = _parse_resume(attrib)
tag = 'RESUME'
else:
data = _parse_un(attrib)
elif (tag == 'TAIKYOKU'):
data = _parse_taikyoku(attrib)
elif (tag == 'SHUFFLE'):
data = _parse_shuffle(attrib)
elif (tag == 'INIT'):
data = _parse_init(attrib)
elif (tag == 'DORA'):
data = _parse_dora(attrib)
elif (tag[0] in {'T', 'U', 'V', 'W'}):
data = _parse_draw(tag)
tag = 'DRAW'
elif (tag[0] in {'D', 'E', 'F', 'G'}):
data = _parse_discard(tag)
tag = 'DISCARD'
elif (tag == 'N'):
data = _parse_call(attrib)
tag = 'CALL'
elif (tag == 'REACH'):
data = _parse_reach(attrib)
elif (tag == 'AGARI'):
data = _parse_agari(attrib)
elif (tag == 'RYUUKYOKU'):
data = _parse_ryuukyoku(attrib)
elif (tag == 'BYE'):
data = _parse_bye(attrib)
else:
raise NotImplementedError('{}: {}'.format(tag, attrib))
_LG.debug('Output: %s: %s', tag, data)
return {'tag': tag, 'data': data}
|
Parse individual XML node of tenhou mjlog.
Parameters
----------
tag : str
Tags such as 'GO', 'DORA', 'AGARI' etc...
attrib: dict or list
Attribute of the node
Returns
-------
dict
JSON object
|
tenhou_log_utils/parser.py
|
parse_node
|
georeth/tenhou-log-utils
| 15 |
python
|
def parse_node(tag, attrib):
"Parse individual XML node of tenhou mjlog.\n\n Parameters\n ----------\n tag : str\n Tags such as 'GO', 'DORA', 'AGARI' etc...\n\n attrib: dict or list\n Attribute of the node\n\n Returns\n -------\n dict\n JSON object\n "
attrib = _ensure_unicode(attrib)
_LG.debug('Input: %s: %s', tag, attrib)
if (tag == 'GO'):
data = _parse_go(attrib)
elif (tag == 'UN'):
if (len(attrib) == 1):
data = _parse_resume(attrib)
tag = 'RESUME'
else:
data = _parse_un(attrib)
elif (tag == 'TAIKYOKU'):
data = _parse_taikyoku(attrib)
elif (tag == 'SHUFFLE'):
data = _parse_shuffle(attrib)
elif (tag == 'INIT'):
data = _parse_init(attrib)
elif (tag == 'DORA'):
data = _parse_dora(attrib)
elif (tag[0] in {'T', 'U', 'V', 'W'}):
data = _parse_draw(tag)
tag = 'DRAW'
elif (tag[0] in {'D', 'E', 'F', 'G'}):
data = _parse_discard(tag)
tag = 'DISCARD'
elif (tag == 'N'):
data = _parse_call(attrib)
tag = 'CALL'
elif (tag == 'REACH'):
data = _parse_reach(attrib)
elif (tag == 'AGARI'):
data = _parse_agari(attrib)
elif (tag == 'RYUUKYOKU'):
data = _parse_ryuukyoku(attrib)
elif (tag == 'BYE'):
data = _parse_bye(attrib)
else:
raise NotImplementedError('{}: {}'.format(tag, attrib))
_LG.debug('Output: %s: %s', tag, data)
return {'tag': tag, 'data': data}
|
def parse_node(tag, attrib):
"Parse individual XML node of tenhou mjlog.\n\n Parameters\n ----------\n tag : str\n Tags such as 'GO', 'DORA', 'AGARI' etc...\n\n attrib: dict or list\n Attribute of the node\n\n Returns\n -------\n dict\n JSON object\n "
attrib = _ensure_unicode(attrib)
_LG.debug('Input: %s: %s', tag, attrib)
if (tag == 'GO'):
data = _parse_go(attrib)
elif (tag == 'UN'):
if (len(attrib) == 1):
data = _parse_resume(attrib)
tag = 'RESUME'
else:
data = _parse_un(attrib)
elif (tag == 'TAIKYOKU'):
data = _parse_taikyoku(attrib)
elif (tag == 'SHUFFLE'):
data = _parse_shuffle(attrib)
elif (tag == 'INIT'):
data = _parse_init(attrib)
elif (tag == 'DORA'):
data = _parse_dora(attrib)
elif (tag[0] in {'T', 'U', 'V', 'W'}):
data = _parse_draw(tag)
tag = 'DRAW'
elif (tag[0] in {'D', 'E', 'F', 'G'}):
data = _parse_discard(tag)
tag = 'DISCARD'
elif (tag == 'N'):
data = _parse_call(attrib)
tag = 'CALL'
elif (tag == 'REACH'):
data = _parse_reach(attrib)
elif (tag == 'AGARI'):
data = _parse_agari(attrib)
elif (tag == 'RYUUKYOKU'):
data = _parse_ryuukyoku(attrib)
elif (tag == 'BYE'):
data = _parse_bye(attrib)
else:
raise NotImplementedError('{}: {}'.format(tag, attrib))
_LG.debug('Output: %s: %s', tag, data)
return {'tag': tag, 'data': data}<|docstring|>Parse individual XML node of tenhou mjlog.
Parameters
----------
tag : str
Tags such as 'GO', 'DORA', 'AGARI' etc...
attrib: dict or list
Attribute of the node
Returns
-------
dict
JSON object<|endoftext|>
|
acb622d8bdb5ca1518c55bc96fb540d9f402e3f92789d8eba1a4226acb0644a4
|
def _structure_parsed_result(parsed):
"Add structure to parsed log data\n\n Parameters\n ----------\n parsed : list of dict\n Each item in list corresponds to an XML node in original mjlog file.\n\n Returns\n -------\n dict\n On top level, 'meta' and 'rounds' key are defined. 'meta' contains\n 'SHUFFLE', 'GO', 'UN' and 'TAIKYOKU' keys and its parsed results as\n values. 'rounds' is a list of which items correspond to one round of\n game play.\n "
round_ = None
game = {'meta': {}, 'rounds': []}
for item in parsed:
(tag, data) = (item['tag'], item['data'])
if (tag in ['SHUFFLE', 'GO', 'UN', 'TAIKYOKU']):
game['meta'][tag] = data
elif (tag == 'INIT'):
if (round_ is not None):
game['rounds'].append(round_)
round_ = [item]
else:
round_.append(item)
game['rounds'].append(round_)
_validate_structure(parsed, game['meta'], game['rounds'])
return game
|
Add structure to parsed log data
Parameters
----------
parsed : list of dict
Each item in list corresponds to an XML node in original mjlog file.
Returns
-------
dict
On top level, 'meta' and 'rounds' key are defined. 'meta' contains
'SHUFFLE', 'GO', 'UN' and 'TAIKYOKU' keys and its parsed results as
values. 'rounds' is a list of which items correspond to one round of
game play.
|
tenhou_log_utils/parser.py
|
_structure_parsed_result
|
georeth/tenhou-log-utils
| 15 |
python
|
def _structure_parsed_result(parsed):
"Add structure to parsed log data\n\n Parameters\n ----------\n parsed : list of dict\n Each item in list corresponds to an XML node in original mjlog file.\n\n Returns\n -------\n dict\n On top level, 'meta' and 'rounds' key are defined. 'meta' contains\n 'SHUFFLE', 'GO', 'UN' and 'TAIKYOKU' keys and its parsed results as\n values. 'rounds' is a list of which items correspond to one round of\n game play.\n "
round_ = None
game = {'meta': {}, 'rounds': []}
for item in parsed:
(tag, data) = (item['tag'], item['data'])
if (tag in ['SHUFFLE', 'GO', 'UN', 'TAIKYOKU']):
game['meta'][tag] = data
elif (tag == 'INIT'):
if (round_ is not None):
game['rounds'].append(round_)
round_ = [item]
else:
round_.append(item)
game['rounds'].append(round_)
_validate_structure(parsed, game['meta'], game['rounds'])
return game
|
def _structure_parsed_result(parsed):
"Add structure to parsed log data\n\n Parameters\n ----------\n parsed : list of dict\n Each item in list corresponds to an XML node in original mjlog file.\n\n Returns\n -------\n dict\n On top level, 'meta' and 'rounds' key are defined. 'meta' contains\n 'SHUFFLE', 'GO', 'UN' and 'TAIKYOKU' keys and its parsed results as\n values. 'rounds' is a list of which items correspond to one round of\n game play.\n "
round_ = None
game = {'meta': {}, 'rounds': []}
for item in parsed:
(tag, data) = (item['tag'], item['data'])
if (tag in ['SHUFFLE', 'GO', 'UN', 'TAIKYOKU']):
game['meta'][tag] = data
elif (tag == 'INIT'):
if (round_ is not None):
game['rounds'].append(round_)
round_ = [item]
else:
round_.append(item)
game['rounds'].append(round_)
_validate_structure(parsed, game['meta'], game['rounds'])
return game<|docstring|>Add structure to parsed log data
Parameters
----------
parsed : list of dict
Each item in list corresponds to an XML node in original mjlog file.
Returns
-------
dict
On top level, 'meta' and 'rounds' key are defined. 'meta' contains
'SHUFFLE', 'GO', 'UN' and 'TAIKYOKU' keys and its parsed results as
values. 'rounds' is a list of which items correspond to one round of
game play.<|endoftext|>
|
23b7520b7ad7ec1e53efbcec319f475d21ad09e3d1a4aaa431c781872ab764e0
|
def parse_mjlog(root_node, tags=None):
'Convert mjlog XML node into JSON\n\n Parameters\n ----------\n root_node (Element)\n Root node of mjlog XML data.\n\n tag : list of str\n When present, only the given tags are parsed and no post-processing\n is carried out.\n\n Returns\n -------\n dict\n Dictionary of of child nodes parsed.\n '
parsed = []
for node in root_node:
if ((tags is None) or (node.tag in tags)):
parsed.append(parse_node(node.tag, node.attrib))
if (tags is None):
return _structure_parsed_result(parsed)
return parsed
|
Convert mjlog XML node into JSON
Parameters
----------
root_node (Element)
Root node of mjlog XML data.
tag : list of str
When present, only the given tags are parsed and no post-processing
is carried out.
Returns
-------
dict
Dictionary of of child nodes parsed.
|
tenhou_log_utils/parser.py
|
parse_mjlog
|
georeth/tenhou-log-utils
| 15 |
python
|
def parse_mjlog(root_node, tags=None):
'Convert mjlog XML node into JSON\n\n Parameters\n ----------\n root_node (Element)\n Root node of mjlog XML data.\n\n tag : list of str\n When present, only the given tags are parsed and no post-processing\n is carried out.\n\n Returns\n -------\n dict\n Dictionary of of child nodes parsed.\n '
parsed = []
for node in root_node:
if ((tags is None) or (node.tag in tags)):
parsed.append(parse_node(node.tag, node.attrib))
if (tags is None):
return _structure_parsed_result(parsed)
return parsed
|
def parse_mjlog(root_node, tags=None):
'Convert mjlog XML node into JSON\n\n Parameters\n ----------\n root_node (Element)\n Root node of mjlog XML data.\n\n tag : list of str\n When present, only the given tags are parsed and no post-processing\n is carried out.\n\n Returns\n -------\n dict\n Dictionary of of child nodes parsed.\n '
parsed = []
for node in root_node:
if ((tags is None) or (node.tag in tags)):
parsed.append(parse_node(node.tag, node.attrib))
if (tags is None):
return _structure_parsed_result(parsed)
return parsed<|docstring|>Convert mjlog XML node into JSON
Parameters
----------
root_node (Element)
Root node of mjlog XML data.
tag : list of str
When present, only the given tags are parsed and no post-processing
is carried out.
Returns
-------
dict
Dictionary of of child nodes parsed.<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.