max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111 values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
src/core/python/tests/test_config.py | railtoolkit/OpenLinTim | 0 | 6617051 | import logging
import unittest
from core.solver.generic_solver_interface import SolverType
from core.util.config import Config
class ConfigTest(unittest.TestCase):
def test_add_values(self):
config = Config()
config.put("test", "abc")
config.put("test2", 2)
config.put("test3", True)
self.assertEqual(3, len(config.data))
config.put("test3", 5.3)
self.assertEqual(3, len(config.data))
def test_read_values(self):
config = Config()
config.put("test", "abc")
config.put("test2", 2)
config.put("test3", True)
config.put("test4", 5.3)
config.put("test5", "FATAL")
config.put("test6", "XPRESS")
self.assertEqual("abc", config.getStringValue("test"))
self.assertEqual(2, config.getIntegerValue("test2"))
self.assertEqual(True, config.getBooleanValue("test3"))
self.assertEqual(5.3, config.getDoubleValue("test4"))
self.assertEqual(logging.CRITICAL, config.getLogLevel("test5"))
self.assertEqual(SolverType.XPRESS, config.getSolverType("test6"))
| import logging
import unittest
from core.solver.generic_solver_interface import SolverType
from core.util.config import Config
class ConfigTest(unittest.TestCase):
def test_add_values(self):
config = Config()
config.put("test", "abc")
config.put("test2", 2)
config.put("test3", True)
self.assertEqual(3, len(config.data))
config.put("test3", 5.3)
self.assertEqual(3, len(config.data))
def test_read_values(self):
config = Config()
config.put("test", "abc")
config.put("test2", 2)
config.put("test3", True)
config.put("test4", 5.3)
config.put("test5", "FATAL")
config.put("test6", "XPRESS")
self.assertEqual("abc", config.getStringValue("test"))
self.assertEqual(2, config.getIntegerValue("test2"))
self.assertEqual(True, config.getBooleanValue("test3"))
self.assertEqual(5.3, config.getDoubleValue("test4"))
self.assertEqual(logging.CRITICAL, config.getLogLevel("test5"))
self.assertEqual(SolverType.XPRESS, config.getSolverType("test6"))
| none | 1 | 2.685845 | 3 | |
apysc/_type/any_value.py | simon-ritchie/apyscript | 16 | 6617052 | <gh_stars>10-100
"""Class implementation of any value.
"""
from typing import Any
from typing import Dict
from apysc._event.custom_event_interface import CustomEventInterface
from apysc._type.boolean import Boolean
from apysc._type.copy_interface import CopyInterface
from apysc._type.revert_interface import RevertInterface
from apysc._type.variable_name_interface import VariableNameInterface
class AnyValue(CopyInterface, RevertInterface, CustomEventInterface):
"""
Class implementation of any value (value that can't determine type).
"""
_value: Any
def __init__(self, value: Any) -> None:
"""
Class implementation of any value (value that can't determine
type).
Parameters
----------
value : *
Initial any value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__init__', locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._expression import expression_variables_util
from apysc._expression import var_names
TYPE_NAME: str = var_names.ANY
self._value = value
self.variable_name = expression_variables_util.\
get_next_variable_name(type_name=TYPE_NAME)
self._type_name = TYPE_NAME
self._append_constructor_expression()
def _append_constructor_expression(self) -> None:
"""
Append constructor expression.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self._append_constructor_expression,
locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._type import value_util
expression: str = f'var {self.variable_name} = '
if isinstance(self._value, VariableNameInterface):
expression += f'{self._value.variable_name};'
else:
value_str: str = value_util.get_value_str_for_expression(
value=self._value)
expression += f'{value_str};'
ap.append_js_expression(expression=expression)
@property
def value(self) -> Any:
"""
Get a current value.
Returns
-------
value : *
Any value.
"""
return self._value
@value.setter
def value(self, value: Any) -> None:
"""
Set a any value.
Parameters
----------
value : *
Any value to set.
"""
import apysc as ap
with ap.DebugInfo(
callable_='value', locals_=locals(),
module_name=__name__, class_=AnyValue):
self._value = value
self._append_value_setter_expression(value=value)
def _append_value_setter_expression(self, *, value: Any) -> None:
"""
Append value's setter expression.
Parameters
----------
value : *
Any value to set.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self._append_value_setter_expression,
locals_=locals(),
module_name=__name__, class_=AnyValue):
expression: str = f'{self.variable_name} = '
if isinstance(value, VariableNameInterface):
expression += f'{value.variable_name};'
else:
expression += f'{value};'
ap.append_js_expression(expression=expression)
def _append_arithmetic_operation_expression(
self, *, other: Any, operator: str) -> VariableNameInterface:
"""
Append arithmetic operation (e.g., addition) expression.
Parameters
----------
other : Any
Other value to use.
operator : str
JavaScript arithmetic operator, like '+', '*', and so on.
Returns
-------
result : AnyValue
Calculated result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self._append_arithmetic_operation_expression,
locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._type.value_util import get_value_str_for_expression
value_str: str = get_value_str_for_expression(value=other)
result: AnyValue = self._copy()
expression: str = (
f'{result.variable_name} = '
f'{self.variable_name} {operator} {value_str};'
)
ap.append_js_expression(expression=expression)
return result
def __add__(self, other: Any) -> Any:
"""
Method for addition.
Parameters
----------
other : Any
Other value to add.
Returns
-------
result : AnyValue
Addition result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__add__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: VariableNameInterface = \
self._append_arithmetic_operation_expression(
other=other, operator='+')
return result
def __sub__(self, other: Any) -> Any:
"""
Method for subtraction.
Parameters
----------
other : Any
Other value to subtract.
Returns
-------
result : AnyValue
Subtraction result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__sub__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: VariableNameInterface = \
self._append_arithmetic_operation_expression(
other=other, operator='-')
return result
def __mul__(self, other: Any) -> Any:
"""
Method for multiplication.
Parameters
----------
other : Any
Other value to multiply.
Returns
-------
result : AnyValue
Subtraction result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__mul__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: VariableNameInterface = \
self._append_arithmetic_operation_expression(
other=other, operator='*')
return result
def __truediv__(self, other: Any) -> Any:
"""
Method for true division.
Parameters
----------
other : Any
Other value for true division.
Returns
-------
result : AnyValue
True division result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__truediv__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: VariableNameInterface = \
self._append_arithmetic_operation_expression(
other=other, operator='/')
return result
def __floordiv__(self, other: Any) -> Any:
"""
Method for floor division.
Parameters
----------
other : Any
Other value for floor division.
Returns
-------
result : AnyValue
Floor division result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__floordiv__', locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._type.value_util import get_value_str_for_expression
result: AnyValue = self._copy()
value_str: str = get_value_str_for_expression(value=other)
expression: str = (
f'{result.variable_name} = '
f'parseInt({self.variable_name} / {value_str});'
)
ap.append_js_expression(expression=expression)
return result
def _append_incremental_arithmetic_operation_expression(
self, *, other: Any, operator: str) -> None:
"""
Append incremental arithmetic operation (e.g., incremental
addition) expression.
Parameters
----------
other : Any
Other value to use.
operator : str
JavaScript arithmetic operator, like '+=', '*=', and so on.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self._append_incremental_arithmetic_operation_expression, # noqa
locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._type.value_util import get_value_str_for_expression
value_str: str = get_value_str_for_expression(value=other)
expression: str = (
f'{self.variable_name} {operator} {value_str};'
)
ap.append_js_expression(expression=expression)
def __iadd__(self, other: Any) -> Any:
"""
Method for incremental addition.
Parameters
----------
other : Any
Other value for incremental addition.
Returns
-------
result : AnyValue
Incremental addition result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__iadd__', locals_=locals(),
module_name=__name__, class_=AnyValue):
self._append_incremental_arithmetic_operation_expression(
other=other, operator='+=')
return self
def __isub__(self, other: Any) -> Any:
"""
Method for incremental subtraction.
Parameters
----------
other : Any
Other value for incremental subtraction.
Returns
-------
result : AnyValue
Incremental subtraction result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__isub__', locals_=locals(),
module_name=__name__, class_=AnyValue):
self._append_incremental_arithmetic_operation_expression(
other=other, operator='-=')
return self
def __imul__(self, other: Any) -> Any:
"""
Method for incremental multiplication.
Parameters
----------
other : Any
Other value for incremental multiplication.
Returns
-------
result : AnyValue
Incremental multiplication result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__imul__', locals_=locals(),
module_name=__name__, class_=AnyValue):
self._append_incremental_arithmetic_operation_expression(
other=other, operator='*=')
return self
def __itruediv__(self, other: Any) -> Any:
"""
Method for incremental true division.
Parameters
----------
other : Any
Other value for incremental division.
Returns
-------
result : AnyValue
Incremental division result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__itruediv__', locals_=locals(),
module_name=__name__, class_=AnyValue):
self._append_incremental_arithmetic_operation_expression(
other=other, operator='/=')
return self
def _append_comparison_expression(
self, *, comparison_operator: str, other: Any) -> Boolean:
"""
Append comparison operation expression.
Parameters
----------
comparison_operator : str
JavaScript comparison operator (e.g., '===', '>=',
and so on).
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self._append_comparison_expression,
locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._type.value_util import get_value_str_for_expression
result: ap.Boolean = ap.Boolean(False)
value_str: str = get_value_str_for_expression(value=other)
expression: str = (
f'{result.variable_name} = '
f'{self.variable_name} {comparison_operator} {value_str};'
)
ap.append_js_expression(expression=expression)
return result
def __eq__(self, other: Any) -> Any:
"""
Equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__eq__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='===', other=other)
return result
def __ne__(self, other: Any) -> Any:
"""
Not equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__ne__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='!==', other=other)
return result
def __lt__(self, other: Any) -> Boolean:
"""
Less than comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__lt__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='<', other=other)
return result
def __le__(self, other: Any) -> Boolean:
"""
Less than equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__le__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='<=', other=other)
return result
def __gt__(self, other: Any) -> Boolean:
"""
Greater than comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__gt__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='>', other=other)
return result
def __ge__(self, other: Any) -> Boolean:
"""
Greater than equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__ge__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='>=', other=other)
return result
_any_value_snapshots: Dict[str, Any]
def _make_snapshot(self, *, snapshot_name: str) -> None:
"""
Make value's snapshot.
Parameters
----------
snapshot_name : str
Target snapshot name.
"""
self._set_single_snapshot_val_to_dict(
dict_name='_any_value_snapshots',
value=self._value, snapshot_name=snapshot_name)
def _revert(self, *, snapshot_name: str) -> None:
"""
Revert value if snapshot exists.
Parameters
----------
snapshot_name : str
Target snapshot name.
"""
if not self._snapshot_exists(snapshot_name=snapshot_name):
return
self._value = self._any_value_snapshots[snapshot_name]
| """Class implementation of any value.
"""
from typing import Any
from typing import Dict
from apysc._event.custom_event_interface import CustomEventInterface
from apysc._type.boolean import Boolean
from apysc._type.copy_interface import CopyInterface
from apysc._type.revert_interface import RevertInterface
from apysc._type.variable_name_interface import VariableNameInterface
class AnyValue(CopyInterface, RevertInterface, CustomEventInterface):
"""
Class implementation of any value (value that can't determine type).
"""
_value: Any
def __init__(self, value: Any) -> None:
"""
Class implementation of any value (value that can't determine
type).
Parameters
----------
value : *
Initial any value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__init__', locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._expression import expression_variables_util
from apysc._expression import var_names
TYPE_NAME: str = var_names.ANY
self._value = value
self.variable_name = expression_variables_util.\
get_next_variable_name(type_name=TYPE_NAME)
self._type_name = TYPE_NAME
self._append_constructor_expression()
def _append_constructor_expression(self) -> None:
"""
Append constructor expression.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self._append_constructor_expression,
locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._type import value_util
expression: str = f'var {self.variable_name} = '
if isinstance(self._value, VariableNameInterface):
expression += f'{self._value.variable_name};'
else:
value_str: str = value_util.get_value_str_for_expression(
value=self._value)
expression += f'{value_str};'
ap.append_js_expression(expression=expression)
@property
def value(self) -> Any:
"""
Get a current value.
Returns
-------
value : *
Any value.
"""
return self._value
@value.setter
def value(self, value: Any) -> None:
"""
Set a any value.
Parameters
----------
value : *
Any value to set.
"""
import apysc as ap
with ap.DebugInfo(
callable_='value', locals_=locals(),
module_name=__name__, class_=AnyValue):
self._value = value
self._append_value_setter_expression(value=value)
def _append_value_setter_expression(self, *, value: Any) -> None:
"""
Append value's setter expression.
Parameters
----------
value : *
Any value to set.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self._append_value_setter_expression,
locals_=locals(),
module_name=__name__, class_=AnyValue):
expression: str = f'{self.variable_name} = '
if isinstance(value, VariableNameInterface):
expression += f'{value.variable_name};'
else:
expression += f'{value};'
ap.append_js_expression(expression=expression)
def _append_arithmetic_operation_expression(
self, *, other: Any, operator: str) -> VariableNameInterface:
"""
Append arithmetic operation (e.g., addition) expression.
Parameters
----------
other : Any
Other value to use.
operator : str
JavaScript arithmetic operator, like '+', '*', and so on.
Returns
-------
result : AnyValue
Calculated result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self._append_arithmetic_operation_expression,
locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._type.value_util import get_value_str_for_expression
value_str: str = get_value_str_for_expression(value=other)
result: AnyValue = self._copy()
expression: str = (
f'{result.variable_name} = '
f'{self.variable_name} {operator} {value_str};'
)
ap.append_js_expression(expression=expression)
return result
def __add__(self, other: Any) -> Any:
"""
Method for addition.
Parameters
----------
other : Any
Other value to add.
Returns
-------
result : AnyValue
Addition result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__add__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: VariableNameInterface = \
self._append_arithmetic_operation_expression(
other=other, operator='+')
return result
def __sub__(self, other: Any) -> Any:
"""
Method for subtraction.
Parameters
----------
other : Any
Other value to subtract.
Returns
-------
result : AnyValue
Subtraction result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__sub__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: VariableNameInterface = \
self._append_arithmetic_operation_expression(
other=other, operator='-')
return result
def __mul__(self, other: Any) -> Any:
"""
Method for multiplication.
Parameters
----------
other : Any
Other value to multiply.
Returns
-------
result : AnyValue
Subtraction result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__mul__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: VariableNameInterface = \
self._append_arithmetic_operation_expression(
other=other, operator='*')
return result
def __truediv__(self, other: Any) -> Any:
"""
Method for true division.
Parameters
----------
other : Any
Other value for true division.
Returns
-------
result : AnyValue
True division result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__truediv__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: VariableNameInterface = \
self._append_arithmetic_operation_expression(
other=other, operator='/')
return result
def __floordiv__(self, other: Any) -> Any:
"""
Method for floor division.
Parameters
----------
other : Any
Other value for floor division.
Returns
-------
result : AnyValue
Floor division result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__floordiv__', locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._type.value_util import get_value_str_for_expression
result: AnyValue = self._copy()
value_str: str = get_value_str_for_expression(value=other)
expression: str = (
f'{result.variable_name} = '
f'parseInt({self.variable_name} / {value_str});'
)
ap.append_js_expression(expression=expression)
return result
def _append_incremental_arithmetic_operation_expression(
self, *, other: Any, operator: str) -> None:
"""
Append incremental arithmetic operation (e.g., incremental
addition) expression.
Parameters
----------
other : Any
Other value to use.
operator : str
JavaScript arithmetic operator, like '+=', '*=', and so on.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self._append_incremental_arithmetic_operation_expression, # noqa
locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._type.value_util import get_value_str_for_expression
value_str: str = get_value_str_for_expression(value=other)
expression: str = (
f'{self.variable_name} {operator} {value_str};'
)
ap.append_js_expression(expression=expression)
def __iadd__(self, other: Any) -> Any:
"""
Method for incremental addition.
Parameters
----------
other : Any
Other value for incremental addition.
Returns
-------
result : AnyValue
Incremental addition result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__iadd__', locals_=locals(),
module_name=__name__, class_=AnyValue):
self._append_incremental_arithmetic_operation_expression(
other=other, operator='+=')
return self
def __isub__(self, other: Any) -> Any:
"""
Method for incremental subtraction.
Parameters
----------
other : Any
Other value for incremental subtraction.
Returns
-------
result : AnyValue
Incremental subtraction result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__isub__', locals_=locals(),
module_name=__name__, class_=AnyValue):
self._append_incremental_arithmetic_operation_expression(
other=other, operator='-=')
return self
def __imul__(self, other: Any) -> Any:
"""
Method for incremental multiplication.
Parameters
----------
other : Any
Other value for incremental multiplication.
Returns
-------
result : AnyValue
Incremental multiplication result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__imul__', locals_=locals(),
module_name=__name__, class_=AnyValue):
self._append_incremental_arithmetic_operation_expression(
other=other, operator='*=')
return self
def __itruediv__(self, other: Any) -> Any:
"""
Method for incremental true division.
Parameters
----------
other : Any
Other value for incremental division.
Returns
-------
result : AnyValue
Incremental division result value.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__itruediv__', locals_=locals(),
module_name=__name__, class_=AnyValue):
self._append_incremental_arithmetic_operation_expression(
other=other, operator='/=')
return self
def _append_comparison_expression(
self, *, comparison_operator: str, other: Any) -> Boolean:
"""
Append comparison operation expression.
Parameters
----------
comparison_operator : str
JavaScript comparison operator (e.g., '===', '>=',
and so on).
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self._append_comparison_expression,
locals_=locals(),
module_name=__name__, class_=AnyValue):
from apysc._type.value_util import get_value_str_for_expression
result: ap.Boolean = ap.Boolean(False)
value_str: str = get_value_str_for_expression(value=other)
expression: str = (
f'{result.variable_name} = '
f'{self.variable_name} {comparison_operator} {value_str};'
)
ap.append_js_expression(expression=expression)
return result
def __eq__(self, other: Any) -> Any:
"""
Equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__eq__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='===', other=other)
return result
def __ne__(self, other: Any) -> Any:
"""
Not equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__ne__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='!==', other=other)
return result
def __lt__(self, other: Any) -> Boolean:
"""
Less than comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__lt__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='<', other=other)
return result
def __le__(self, other: Any) -> Boolean:
"""
Less than equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__le__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='<=', other=other)
return result
def __gt__(self, other: Any) -> Boolean:
"""
Greater than comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__gt__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='>', other=other)
return result
def __ge__(self, other: Any) -> Boolean:
"""
Greater than equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible.
"""
import apysc as ap
with ap.DebugInfo(
callable_='__ge__', locals_=locals(),
module_name=__name__, class_=AnyValue):
result: ap.Boolean = self._append_comparison_expression(
comparison_operator='>=', other=other)
return result
_any_value_snapshots: Dict[str, Any]
def _make_snapshot(self, *, snapshot_name: str) -> None:
"""
Make value's snapshot.
Parameters
----------
snapshot_name : str
Target snapshot name.
"""
self._set_single_snapshot_val_to_dict(
dict_name='_any_value_snapshots',
value=self._value, snapshot_name=snapshot_name)
def _revert(self, *, snapshot_name: str) -> None:
"""
Revert value if snapshot exists.
Parameters
----------
snapshot_name : str
Target snapshot name.
"""
if not self._snapshot_exists(snapshot_name=snapshot_name):
return
self._value = self._any_value_snapshots[snapshot_name] | en | 0.478989 | Class implementation of any value. Class implementation of any value (value that can't determine type). Class implementation of any value (value that can't determine
type).
Parameters
----------
value : *
Initial any value. Append constructor expression. Get a current value.
Returns
-------
value : *
Any value. Set a any value.
Parameters
----------
value : *
Any value to set. Append value's setter expression.
Parameters
----------
value : *
Any value to set. Append arithmetic operation (e.g., addition) expression.
Parameters
----------
other : Any
Other value to use.
operator : str
JavaScript arithmetic operator, like '+', '*', and so on.
Returns
-------
result : AnyValue
Calculated result value. Method for addition.
Parameters
----------
other : Any
Other value to add.
Returns
-------
result : AnyValue
Addition result value. Method for subtraction.
Parameters
----------
other : Any
Other value to subtract.
Returns
-------
result : AnyValue
Subtraction result value. Method for multiplication.
Parameters
----------
other : Any
Other value to multiply.
Returns
-------
result : AnyValue
Subtraction result value. Method for true division.
Parameters
----------
other : Any
Other value for true division.
Returns
-------
result : AnyValue
True division result value. Method for floor division.
Parameters
----------
other : Any
Other value for floor division.
Returns
-------
result : AnyValue
Floor division result value. Append incremental arithmetic operation (e.g., incremental
addition) expression.
Parameters
----------
other : Any
Other value to use.
operator : str
JavaScript arithmetic operator, like '+=', '*=', and so on. # noqa Method for incremental addition.
Parameters
----------
other : Any
Other value for incremental addition.
Returns
-------
result : AnyValue
Incremental addition result value. Method for incremental subtraction.
Parameters
----------
other : Any
Other value for incremental subtraction.
Returns
-------
result : AnyValue
Incremental subtraction result value. Method for incremental multiplication.
Parameters
----------
other : Any
Other value for incremental multiplication.
Returns
-------
result : AnyValue
Incremental multiplication result value. Method for incremental true division.
Parameters
----------
other : Any
Other value for incremental division.
Returns
-------
result : AnyValue
Incremental division result value. Append comparison operation expression.
Parameters
----------
comparison_operator : str
JavaScript comparison operator (e.g., '===', '>=',
and so on).
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible. Equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible. Not equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible. Less than comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible. Less than equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible. Greater than comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible. Greater than equal comparison method.
Parameters
----------
other : Any
Other value to compare.
Returns
-------
result : Boolean
Comparison result. This will always be False on Python
since correct comparison is not possible. Make value's snapshot.
Parameters
----------
snapshot_name : str
Target snapshot name. Revert value if snapshot exists.
Parameters
----------
snapshot_name : str
Target snapshot name. | 2.698029 | 3 |
cryptoportfolio/interfaces/wallets/cardano.py | a1fred/cryptoportfolio | 7 | 6617053 | from decimal import Decimal
import requests
from cryptoportfolio.interfaces.base import CryptoCoinWallet
class CardanoWallet(CryptoCoinWallet):
decimal_places = 18
def _get_addr_coins_and_tokens_balance(self):
balance_data = requests.get("https://cardanoexplorer.com/api/addresses/summary/%s" % self.addr).json()
balance = balance_data['Right']['caBalance']['getCoin']
return [
("ADA", Decimal(balance) / Decimal(1000000)),
]
| from decimal import Decimal
import requests
from cryptoportfolio.interfaces.base import CryptoCoinWallet
class CardanoWallet(CryptoCoinWallet):
decimal_places = 18
def _get_addr_coins_and_tokens_balance(self):
balance_data = requests.get("https://cardanoexplorer.com/api/addresses/summary/%s" % self.addr).json()
balance = balance_data['Right']['caBalance']['getCoin']
return [
("ADA", Decimal(balance) / Decimal(1000000)),
]
| none | 1 | 2.934197 | 3 | |
game/combat/agent/agentrand.py | Sipondo/ulix-dexflow | 5 | 6617054 | <reponame>Sipondo/ulix-dexflow
import numpy as np
from .baseagent import BaseAgent
from ..action import Action, ActionType
from ..combatscene import CombatState
class AgentRand(BaseAgent):
def start(self):
if self.scene.battle_state != CombatState.BEFORE_START:
return
action_i = np.random.randint(
len(
self.scene.board.get_actor(
(self.team, self.scene.board.get_active(self.team))
).actions
)
)
user = (self.team, self.scene.board.get_active(self.team))
target_team = np.random.randint(len(self.scene.board.teams))
while target_team == self.team:
target_team = np.random.randint(len(self.scene.board.teams))
target = (target_team, self.scene.board.get_active(target_team))
action = Action(
ActionType.ATTACK,
a_index=action_i,
a_data=self.scene.board.get_actor(user).actions[action_i],
user=user,
target=target
)
self.action = action
def get_action(self):
return self.action
| import numpy as np
from .baseagent import BaseAgent
from ..action import Action, ActionType
from ..combatscene import CombatState
class AgentRand(BaseAgent):
def start(self):
if self.scene.battle_state != CombatState.BEFORE_START:
return
action_i = np.random.randint(
len(
self.scene.board.get_actor(
(self.team, self.scene.board.get_active(self.team))
).actions
)
)
user = (self.team, self.scene.board.get_active(self.team))
target_team = np.random.randint(len(self.scene.board.teams))
while target_team == self.team:
target_team = np.random.randint(len(self.scene.board.teams))
target = (target_team, self.scene.board.get_active(target_team))
action = Action(
ActionType.ATTACK,
a_index=action_i,
a_data=self.scene.board.get_actor(user).actions[action_i],
user=user,
target=target
)
self.action = action
def get_action(self):
return self.action | none | 1 | 2.528588 | 3 | |
backend/ml/utils.py | timchenko24/djangorest-vessels-voyages | 0 | 6617055 | <reponame>timchenko24/djangorest-vessels-voyages
from django.http import Http404
from .queries import queries
from sklearn.preprocessing import StandardScaler, MinMaxScaler, FunctionTransformer
import numpy as np
import pandas as pd
def get_query_data(key):
try:
return queries[key]
except KeyError:
raise Http404
def label_clustered_data(df, labels):
return [{'x': col1, 'y': col2, 'label': lbl}
for col1, col2, lbl in zip(df[list(df.columns)[0]], df[list(df.columns)[1]], labels)]
def process_query_params(df, params):
new_df = df
conditions = {
"log": FunctionTransformer(np.log1p, validate=True).transform,
"std": StandardScaler().fit_transform,
"minmax": MinMaxScaler().fit_transform
}
for key in params.keys():
if key in conditions:
new_df = conditions[key](df)
return pd.DataFrame(new_df, index=df.index, columns=df.columns)
| from django.http import Http404
from .queries import queries
from sklearn.preprocessing import StandardScaler, MinMaxScaler, FunctionTransformer
import numpy as np
import pandas as pd
def get_query_data(key):
try:
return queries[key]
except KeyError:
raise Http404
def label_clustered_data(df, labels):
return [{'x': col1, 'y': col2, 'label': lbl}
for col1, col2, lbl in zip(df[list(df.columns)[0]], df[list(df.columns)[1]], labels)]
def process_query_params(df, params):
new_df = df
conditions = {
"log": FunctionTransformer(np.log1p, validate=True).transform,
"std": StandardScaler().fit_transform,
"minmax": MinMaxScaler().fit_transform
}
for key in params.keys():
if key in conditions:
new_df = conditions[key](df)
return pd.DataFrame(new_df, index=df.index, columns=df.columns) | none | 1 | 2.428837 | 2 | |
src/types-reference/lists.py | luismayta/python-example-graphene | 2 | 6617056 | <filename>src/types-reference/lists.py
import graphene
class Character(graphene.ObjectType):
name = graphene.String(required=True)
appears_in = graphene.List(graphene.String())
schema = graphene.Schema(query=Character)
result = schema.execute('{ name, appears_in }')
print(result.data)
| <filename>src/types-reference/lists.py
import graphene
class Character(graphene.ObjectType):
name = graphene.String(required=True)
appears_in = graphene.List(graphene.String())
schema = graphene.Schema(query=Character)
result = schema.execute('{ name, appears_in }')
print(result.data)
| none | 1 | 2.5855 | 3 | |
text.py | joelwright-dev/the-weird-world | 0 | 6617057 | import pygame
class Text(pygame.sprite.Sprite):
def __init__(self, text, color, surface, pos, size):
super().__init__()
font = pygame.font.Font('graphics/fonts/WayfarersToyBoxRegular-gxxER.ttf', size)
self.textobj = font.render(text, 1, color)
self.textrect = self.textobj.get_rect(center = pos)
self.surface = surface
def draw(self):
self.surface.blit(self.textobj, self.textrect) | import pygame
class Text(pygame.sprite.Sprite):
def __init__(self, text, color, surface, pos, size):
super().__init__()
font = pygame.font.Font('graphics/fonts/WayfarersToyBoxRegular-gxxER.ttf', size)
self.textobj = font.render(text, 1, color)
self.textrect = self.textobj.get_rect(center = pos)
self.surface = surface
def draw(self):
self.surface.blit(self.textobj, self.textrect) | none | 1 | 3.092417 | 3 | |
lazy/io/pathz_v2/aiopathz/handle.py | trisongz/lazycls | 2 | 6617058 | <gh_stars>1-10
from __future__ import annotations
import io
from inspect import iscoroutinefunction
from contextlib import asynccontextmanager
from typing import AsyncContextManager
from anyio import AsyncFile, open_file
from aiofile import AIOFile, LineReader
from typing import AsyncIterable, Union, TYPE_CHECKING, Optional, cast, Tuple
from ..pathlibz import Path
from .types import Final, FileMode
if TYPE_CHECKING: # keep mypy quiet
from ..base import PathzPath
BEGINNING: Final[int] = 0
CHUNK_SIZE: Final[int] = 4 * 1_024
SEP: Final[str] = '\n'
ENCODING: Final[str] = 'utf-8'
ERRORS: Final[str] = 'replace'
Paths = Union['PathzPath', Path, str]
FileData = Union[bytes, str]
class IterableAIOFile(AIOFile):
def __init__(
self,
*args,
errors: Optional[str] = ERRORS,
newline: Optional[str] = SEP,
**kwargs
):
super().__init__(*args, **kwargs)
self._errors: Optional[str] = errors
self._newline: Optional[str] = newline
self._offset: int = 0
def __aiter__(self) -> AsyncIterable[str]:
encoding, errors, line_sep = self._get_options()
return read_lines(
self.name,
line_sep,
encoding=encoding,
errors=errors,
)
def _set_offset(self, offset: int, data: FileData):
self._offset = offset + len(data)
def _get_options(
self,
encoding: Optional[str] = None,
errors: Optional[str] = None
) -> Tuple[str, str, str]:
encoding = encoding or self.encoding or ENCODING
errors = errors or self._errors or ERRORS
line_sep: str = self._newline or SEP
return encoding, errors, line_sep
async def read_text(
self,
encoding: Optional[str] = None,
errors: Optional[str] = None
) -> str:
encoding, errors, line_sep = self._get_options(encoding, errors)
return await read_full_file(
self.name,
line_sep,
encoding=encoding,
errors=errors
)
async def read(
self,
size: int = -1,
offset: Optional[int] = None
) -> FileData:
if offset is None:
offset = self._offset
data: FileData = await super().read(size, offset)
self._set_offset(offset, data)
return data
async def write(
self,
data: FileData,
offset: Optional[int] = None
):
if offset is None:
offset = self._offset
await super().write(data, offset)
self._set_offset(offset, data)
async def read_lines(
path: Paths,
line_sep: str = SEP,
chunk_size: int = CHUNK_SIZE,
offset: int = BEGINNING,
encoding: str = ENCODING,
errors: str = ERRORS,
**kwargs
) -> AsyncIterable[str]:
if hasattr(path, 'resolve'):
if iscoroutinefunction(path.resolve):
path = str(await path.resolve())
else:
path = str(path.resolve())
path = cast(str, path)
async with AIOFile(path, 'rb') as handle:
reader = LineReader(
handle,
line_sep=line_sep,
chunk_size=chunk_size,
offset=offset
)
while True:
line: bytes = await reader.readline()
if not line: break
yield line.decode(encoding, errors=errors)
async def read_full_file(
path: Paths,
line_sep: str = SEP,
chunk_size: int = CHUNK_SIZE,
offset: int = BEGINNING,
encoding: str = ENCODING,
errors: str = ERRORS,
**kwargs
) -> str:
lines_gen = read_lines(
path,
line_sep=line_sep,
chunk_size=chunk_size,
offset=offset,
encoding=encoding,
errors=errors
)
with io.StringIO() as string:
async for line in lines_gen:
string.write(line)
return string.getvalue()
Handle = AsyncFile
@asynccontextmanager
async def get_handle(
name: str,
mode: FileMode = 'r',
buffering: int = -1,
encoding: str | None = ENCODING,
errors: str | None = ERRORS,
newline: str | None = SEP,
) -> AsyncContextManager[Handle]:
file: AsyncFile
if 'b' in mode:
file = await open_file(name, mode)
else:
file = await open_file(
name,
mode,
encoding=encoding,
errors=errors,
newline=newline,
)
yield file
await file.aclose() | from __future__ import annotations
import io
from inspect import iscoroutinefunction
from contextlib import asynccontextmanager
from typing import AsyncContextManager
from anyio import AsyncFile, open_file
from aiofile import AIOFile, LineReader
from typing import AsyncIterable, Union, TYPE_CHECKING, Optional, cast, Tuple
from ..pathlibz import Path
from .types import Final, FileMode
if TYPE_CHECKING: # keep mypy quiet
from ..base import PathzPath
BEGINNING: Final[int] = 0
CHUNK_SIZE: Final[int] = 4 * 1_024
SEP: Final[str] = '\n'
ENCODING: Final[str] = 'utf-8'
ERRORS: Final[str] = 'replace'
Paths = Union['PathzPath', Path, str]
FileData = Union[bytes, str]
class IterableAIOFile(AIOFile):
def __init__(
self,
*args,
errors: Optional[str] = ERRORS,
newline: Optional[str] = SEP,
**kwargs
):
super().__init__(*args, **kwargs)
self._errors: Optional[str] = errors
self._newline: Optional[str] = newline
self._offset: int = 0
def __aiter__(self) -> AsyncIterable[str]:
encoding, errors, line_sep = self._get_options()
return read_lines(
self.name,
line_sep,
encoding=encoding,
errors=errors,
)
def _set_offset(self, offset: int, data: FileData):
self._offset = offset + len(data)
def _get_options(
self,
encoding: Optional[str] = None,
errors: Optional[str] = None
) -> Tuple[str, str, str]:
encoding = encoding or self.encoding or ENCODING
errors = errors or self._errors or ERRORS
line_sep: str = self._newline or SEP
return encoding, errors, line_sep
async def read_text(
self,
encoding: Optional[str] = None,
errors: Optional[str] = None
) -> str:
encoding, errors, line_sep = self._get_options(encoding, errors)
return await read_full_file(
self.name,
line_sep,
encoding=encoding,
errors=errors
)
async def read(
self,
size: int = -1,
offset: Optional[int] = None
) -> FileData:
if offset is None:
offset = self._offset
data: FileData = await super().read(size, offset)
self._set_offset(offset, data)
return data
async def write(
self,
data: FileData,
offset: Optional[int] = None
):
if offset is None:
offset = self._offset
await super().write(data, offset)
self._set_offset(offset, data)
async def read_lines(
path: Paths,
line_sep: str = SEP,
chunk_size: int = CHUNK_SIZE,
offset: int = BEGINNING,
encoding: str = ENCODING,
errors: str = ERRORS,
**kwargs
) -> AsyncIterable[str]:
if hasattr(path, 'resolve'):
if iscoroutinefunction(path.resolve):
path = str(await path.resolve())
else:
path = str(path.resolve())
path = cast(str, path)
async with AIOFile(path, 'rb') as handle:
reader = LineReader(
handle,
line_sep=line_sep,
chunk_size=chunk_size,
offset=offset
)
while True:
line: bytes = await reader.readline()
if not line: break
yield line.decode(encoding, errors=errors)
async def read_full_file(
path: Paths,
line_sep: str = SEP,
chunk_size: int = CHUNK_SIZE,
offset: int = BEGINNING,
encoding: str = ENCODING,
errors: str = ERRORS,
**kwargs
) -> str:
lines_gen = read_lines(
path,
line_sep=line_sep,
chunk_size=chunk_size,
offset=offset,
encoding=encoding,
errors=errors
)
with io.StringIO() as string:
async for line in lines_gen:
string.write(line)
return string.getvalue()
Handle = AsyncFile
@asynccontextmanager
async def get_handle(
name: str,
mode: FileMode = 'r',
buffering: int = -1,
encoding: str | None = ENCODING,
errors: str | None = ERRORS,
newline: str | None = SEP,
) -> AsyncContextManager[Handle]:
file: AsyncFile
if 'b' in mode:
file = await open_file(name, mode)
else:
file = await open_file(
name,
mode,
encoding=encoding,
errors=errors,
newline=newline,
)
yield file
await file.aclose() | en | 0.913749 | # keep mypy quiet | 2.397485 | 2 |
org/migrations/0001_initial.py | Ortus-Team/Moim | 0 | 6617059 | <filename>org/migrations/0001_initial.py<gh_stars>0
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-10 08:34
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('tag', '0001_initial'),
('category', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Org',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('created_date', models.DateTimeField(auto_now_add=True, null=True)),
('description', models.CharField(max_length=60000)),
('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='category.Category')),
('members', models.ManyToManyField(to=settings.AUTH_USER_MODEL)),
('tags', models.ManyToManyField(blank=True, to='tag.Tag')),
],
),
]
| <filename>org/migrations/0001_initial.py<gh_stars>0
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-10 08:34
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('tag', '0001_initial'),
('category', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Org',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('created_date', models.DateTimeField(auto_now_add=True, null=True)),
('description', models.CharField(max_length=60000)),
('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='category.Category')),
('members', models.ManyToManyField(to=settings.AUTH_USER_MODEL)),
('tags', models.ManyToManyField(blank=True, to='tag.Tag')),
],
),
]
| en | 0.635502 | # -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-01-10 08:34 | 1.614262 | 2 |
news/filters.py | manavshrivastavagit/django-restapi | 5 | 6617060 | <filename>news/filters.py<gh_stars>1-10
from rest_framework import filters
class TeachersListFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.filter(author=request.user)
class ClassNumberFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.filter(class_number=view.kwargs['class_number'])
class ClassLetterFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
class_letter = request.query_params.get('class_letter', '')
return queryset.filter(class_letter=class_letter) if class_letter else queryset
| <filename>news/filters.py<gh_stars>1-10
from rest_framework import filters
class TeachersListFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.filter(author=request.user)
class ClassNumberFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.filter(class_number=view.kwargs['class_number'])
class ClassLetterFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
class_letter = request.query_params.get('class_letter', '')
return queryset.filter(class_letter=class_letter) if class_letter else queryset
| none | 1 | 2.2851 | 2 | |
apps/usuario/migrations/0001_initial.py | JasonUPP/POA-SER | 0 | 6617061 | <filename>apps/usuario/migrations/0001_initial.py
# Generated by Django 2.1.4 on 2019-01-16 02:38
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Usuario',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=50)),
('apellidoP', models.CharField(max_length=20)),
('apellidoM', models.CharField(max_length=20)),
('correo', models.EmailField(max_length=254)),
('sexo', models.CharField(max_length=10)),
('edad', models.IntegerField()),
('nacimiento', models.DateField()),
('telefono', models.IntegerField()),
('domicilio', models.TextField()),
],
),
]
| <filename>apps/usuario/migrations/0001_initial.py
# Generated by Django 2.1.4 on 2019-01-16 02:38
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Usuario',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=50)),
('apellidoP', models.CharField(max_length=20)),
('apellidoM', models.CharField(max_length=20)),
('correo', models.EmailField(max_length=254)),
('sexo', models.CharField(max_length=10)),
('edad', models.IntegerField()),
('nacimiento', models.DateField()),
('telefono', models.IntegerField()),
('domicilio', models.TextField()),
],
),
]
| en | 0.847273 | # Generated by Django 2.1.4 on 2019-01-16 02:38 | 1.811617 | 2 |
run.py | diegoscastanho/LiconIA | 4 | 6617062 | """
@author: <NAME>
https://github.com/diegoscastanho
"""
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication
import sys
from gui_tcc import Ui_MainWindow
import multiprocessing
from lib.create_process import OtimizationProcess
# from lib.create_process import LoadWorksheetProcess
import logging
from lib.communicator import Communicator
from lib.load_excel import LoadExcelFile
import pickle
from lib.figures import PlotGraphics
from lib.communicator import PlotLogs
from os import walk
import pandas as pd
# from lib.optimization import SerialExecution
# General procedures to show the log
logging.basicConfig(
format=(
'%(asctime)s - %(levelname)s: ' +
'(%(filename)s:%(funcName)s at %(lineno)d): %(message)s'),
datefmt='%b %d %H:%M:%S', level=logging.INFO)
class App(QtWidgets.QMainWindow, Ui_MainWindow):
'''
Ui class
'''
def __init__(self, parent=None):
'''
init class
'''
super(App, self).__init__(parent)
self.setupUi(self)
# set develop (True) or use method (False)
if self.exec_method_radiobutton.isChecked():
self.debug_method = False
logging.info("Execution method type: Execution")
if self.debug_method_radiobutton.isChecked():
self.debug_method = True
logging.info("Execution method type: Debug")
# controller start stop process
self.process_pso = 8*[0]
self.process_ga = 8*[0]
self.process_de = 8*[0]
self.cont_process = 1
# Open
self.open_button.clicked.connect(self.handle_button)
# Start / STOP buttons
self.start_pso_0.clicked.connect(lambda:self.start_algorithm(0, "PSO"))
self.start_pso_1.clicked.connect(lambda:self.start_algorithm(1, "PSO"))
self.start_pso_2.clicked.connect(lambda:self.start_algorithm(2, "PSO"))
self.start_pso_3.clicked.connect(lambda:self.start_algorithm(3, "PSO"))
self.start_pso_4.clicked.connect(lambda:self.start_algorithm(4, "PSO"))
self.start_pso_5.clicked.connect(lambda:self.start_algorithm(5, "PSO"))
self.start_pso_6.clicked.connect(lambda:self.start_algorithm(6, "PSO"))
self.start_pso_7.clicked.connect(lambda:self.start_algorithm(7, "PSO"))
self.stop_pso_0.clicked.connect(lambda:self.stop_algorithm(0, "PSO"))
self.stop_pso_1.clicked.connect(lambda:self.stop_algorithm(1, "PSO"))
self.stop_pso_2.clicked.connect(lambda:self.stop_algorithm(2, "PSO"))
self.stop_pso_3.clicked.connect(lambda:self.stop_algorithm(3, "PSO"))
self.stop_pso_4.clicked.connect(lambda:self.stop_algorithm(4, "PSO"))
self.stop_pso_5.clicked.connect(lambda:self.stop_algorithm(5, "PSO"))
self.stop_pso_6.clicked.connect(lambda:self.stop_algorithm(6, "PSO"))
self.stop_pso_7.clicked.connect(lambda:self.stop_algorithm(7, "PSO"))
self.start_ga_0.clicked.connect(lambda:self.start_algorithm(0, "GA"))
self.start_ga_1.clicked.connect(lambda:self.start_algorithm(1, "GA"))
self.start_ga_2.clicked.connect(lambda:self.start_algorithm(2, "GA"))
self.start_ga_3.clicked.connect(lambda:self.start_algorithm(3, "GA"))
self.start_ga_4.clicked.connect(lambda:self.start_algorithm(4, "GA"))
self.start_ga_5.clicked.connect(lambda:self.start_algorithm(5, "GA"))
self.start_ga_6.clicked.connect(lambda:self.start_algorithm(6, "GA"))
self.start_ga_7.clicked.connect(lambda:self.start_algorithm(7, "GA"))
self.stop_ga_0.clicked.connect(lambda:self.stop_algorithm(0, "GA"))
self.stop_ga_1.clicked.connect(lambda:self.stop_algorithm(1, "GA"))
self.stop_ga_2.clicked.connect(lambda:self.stop_algorithm(2, "GA"))
self.stop_ga_3.clicked.connect(lambda:self.stop_algorithm(3, "GA"))
self.stop_ga_4.clicked.connect(lambda:self.stop_algorithm(4, "GA"))
self.stop_ga_5.clicked.connect(lambda:self.stop_algorithm(5, "GA"))
self.stop_ga_6.clicked.connect(lambda:self.stop_algorithm(6, "GA"))
self.stop_ga_7.clicked.connect(lambda:self.stop_algorithm(7, "GA"))
self.start_de_0.clicked.connect(lambda:self.start_algorithm(0, "DE"))
self.start_de_1.clicked.connect(lambda:self.start_algorithm(1, "DE"))
self.start_de_2.clicked.connect(lambda:self.start_algorithm(2, "DE"))
self.start_de_3.clicked.connect(lambda:self.start_algorithm(3, "DE"))
self.start_de_4.clicked.connect(lambda:self.start_algorithm(4, "DE"))
self.start_de_5.clicked.connect(lambda:self.start_algorithm(5, "DE"))
self.start_de_6.clicked.connect(lambda:self.start_algorithm(6, "DE"))
self.start_de_7.clicked.connect(lambda:self.start_algorithm(7, "DE"))
self.stop_de_0.clicked.connect(lambda:self.stop_algorithm(0, "DE"))
self.stop_de_1.clicked.connect(lambda:self.stop_algorithm(1, "DE"))
self.stop_de_2.clicked.connect(lambda:self.stop_algorithm(2, "DE"))
self.stop_de_3.clicked.connect(lambda:self.stop_algorithm(3, "DE"))
self.stop_de_4.clicked.connect(lambda:self.stop_algorithm(4, "DE"))
self.stop_de_5.clicked.connect(lambda:self.stop_algorithm(5, "DE"))
self.stop_de_6.clicked.connect(lambda:self.stop_algorithm(6, "DE"))
self.stop_de_7.clicked.connect(lambda:self.stop_algorithm(7, "DE"))
# Results
self.process_open_button.clicked.connect(self.handle_button_results)
self.plot_graph_button.clicked.connect(lambda:self.plot_graphics())
self.copy_lag0_pushbutton.clicked.connect(lambda:self.copy_text(0))
self.copy_lag1_pushbutton.clicked.connect(lambda:self.copy_text(1))
self.copy_lag2_pushbutton.clicked.connect(lambda:self.copy_text(2))
self.copy_lag3_pushbutton.clicked.connect(lambda:self.copy_text(3))
self.copy_lag4_pushbutton.clicked.connect(lambda:self.copy_text(4))
self.copy_lag5_pushbutton.clicked.connect(lambda:self.copy_text(5))
self.copy_lag6_pushbutton.clicked.connect(lambda:self.copy_text(6))
self.copy_lag7_pushbutton.clicked.connect(lambda:self.copy_text(7))
def handle_button(self):
'''
Open button optimizations algoritms
'''
fileName, _ = QtWidgets.QFileDialog.getOpenFileName(
self, 'Single File', QtCore.QDir.rootPath(), '*.xlsx')
self.open_file_field.setText(fileName)
self.load_worksheet()
def load_worksheet(self):
'''
Load worksheet
'''
self.label_pso_0.setText("Loading worksheet...")
# parent_conn, child_conn = multiprocessing.Pipe()
# process = LoadWorksheetProcess(
# str(0), child_conn, self)
# process.start()
# process.join()
# self.data = process.recv()
# file_path = self.object.open_file_field.text()
self.type_method()
file_path = self.open_file_field.text()
load = LoadExcelFile(file_path, self.debug_method)
self.data = load.run()
def start_algorithm(self, day_lag, method):
'''
Button that starts simulation
'''
self.type_method()
parent_conn, child_conn = multiprocessing.Pipe()
# pso1_label = Communicator(self.pso1_label)
process = OtimizationProcess(
self.cont_process, child_conn, self, day_lag, method)
process.start()
self.cont_process += 1
# self.label_pso_0.setText(parent_conn.recv())
if method == "PSO":
self.process_pso[day_lag] = process
elif method == "DE":
self.process_de[day_lag] = process
elif method == "GA":
self.process_ga[day_lag] = process
logging.info("Start %s -> lag %d " % (method, day_lag))
def stop_algorithm(self, day_lag, method):
'''
Button that stop simulation
'''
# pso1_label = Communicator(self.pso1_label)
if method == "PSO":
self.process_pso[day_lag].terminate()
elif method == "DE":
self.process_de[day_lag].terminate()
elif method == "GA":
self.process_ga[day_lag].terminate()
logging.info("Stop %s -> lag %d " % (method, day_lag))
def handle_button_results(self):
'''
Open button result
'''
logging.info("Loading json file...")
# file_path, test = QtWidgets.QFileDialog.getOpenFileName(
# self, 'Single File', QtCore.QDir.rootPath(), '*.txt')
mypath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select Folder')
_, _, filenames = next(walk(mypath))
self.graph_file_field.setText(mypath)
self.json_data = list()
for file_ in filenames:
aux_path = mypath + "/" + file_
with open(aux_path, 'rb') as handler:
aux_data = pickle.loads(handler.read())
self.json_data.append(aux_data)
self.json_data.sort(key=lambda x: x["obj"].day_lag, reverse=False)
logging.info("Json file load")
self.results_logs()
def results_logs(self):
'''
Creates the results log in the interface
'''
logging.info("Logging the interface")
my_logs = PlotLogs(self)
my_logs.run()
def plot_graphics(self):
'''
Button that plots Graphics
'''
logging.info("Plotting Graphics")
graphics = PlotGraphics(self)
graphics.run()
def copy_text(self, lag):
'''
copies the generated text to the cliboards
'''
ae = self.json_data[lag]['best'].ae
mse = self.json_data[lag]['best'].mse
mape = self.json_data[lag]['best'].mape
arv = self.json_data[lag]['best'].arv
ia = self.json_data[lag]['best'].ia
mae = self.json_data[lag]['best'].mae
rmse = self.json_data[lag]['best'].rmse
mean = self.json_data[lag]['best'].mean
ranking = self.json_data[lag]['best'].ranking
df=pd.DataFrame(columns = [ ae, mse, mape, arv, ia, mae, rmse, mean, ranking])
df.to_clipboard(index=False)
def type_method(self):
'''
type exec method
'''
if self.exec_method_radiobutton.isChecked():
self.debug_method = False
logging.info("Exec method Type: Execution")
if self.debug_method_radiobutton.isChecked():
self.debug_method = True
logging.info("Exec method Type: Debug")
if __name__ == '__main__':
app = QApplication(sys.argv)
form = App()
form.show()
sys.exit(app.exec_())
| """
@author: <NAME>
https://github.com/diegoscastanho
"""
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication
import sys
from gui_tcc import Ui_MainWindow
import multiprocessing
from lib.create_process import OtimizationProcess
# from lib.create_process import LoadWorksheetProcess
import logging
from lib.communicator import Communicator
from lib.load_excel import LoadExcelFile
import pickle
from lib.figures import PlotGraphics
from lib.communicator import PlotLogs
from os import walk
import pandas as pd
# from lib.optimization import SerialExecution
# General procedures to show the log
logging.basicConfig(
format=(
'%(asctime)s - %(levelname)s: ' +
'(%(filename)s:%(funcName)s at %(lineno)d): %(message)s'),
datefmt='%b %d %H:%M:%S', level=logging.INFO)
class App(QtWidgets.QMainWindow, Ui_MainWindow):
'''
Ui class
'''
def __init__(self, parent=None):
'''
init class
'''
super(App, self).__init__(parent)
self.setupUi(self)
# set develop (True) or use method (False)
if self.exec_method_radiobutton.isChecked():
self.debug_method = False
logging.info("Execution method type: Execution")
if self.debug_method_radiobutton.isChecked():
self.debug_method = True
logging.info("Execution method type: Debug")
# controller start stop process
self.process_pso = 8*[0]
self.process_ga = 8*[0]
self.process_de = 8*[0]
self.cont_process = 1
# Open
self.open_button.clicked.connect(self.handle_button)
# Start / STOP buttons
self.start_pso_0.clicked.connect(lambda:self.start_algorithm(0, "PSO"))
self.start_pso_1.clicked.connect(lambda:self.start_algorithm(1, "PSO"))
self.start_pso_2.clicked.connect(lambda:self.start_algorithm(2, "PSO"))
self.start_pso_3.clicked.connect(lambda:self.start_algorithm(3, "PSO"))
self.start_pso_4.clicked.connect(lambda:self.start_algorithm(4, "PSO"))
self.start_pso_5.clicked.connect(lambda:self.start_algorithm(5, "PSO"))
self.start_pso_6.clicked.connect(lambda:self.start_algorithm(6, "PSO"))
self.start_pso_7.clicked.connect(lambda:self.start_algorithm(7, "PSO"))
self.stop_pso_0.clicked.connect(lambda:self.stop_algorithm(0, "PSO"))
self.stop_pso_1.clicked.connect(lambda:self.stop_algorithm(1, "PSO"))
self.stop_pso_2.clicked.connect(lambda:self.stop_algorithm(2, "PSO"))
self.stop_pso_3.clicked.connect(lambda:self.stop_algorithm(3, "PSO"))
self.stop_pso_4.clicked.connect(lambda:self.stop_algorithm(4, "PSO"))
self.stop_pso_5.clicked.connect(lambda:self.stop_algorithm(5, "PSO"))
self.stop_pso_6.clicked.connect(lambda:self.stop_algorithm(6, "PSO"))
self.stop_pso_7.clicked.connect(lambda:self.stop_algorithm(7, "PSO"))
self.start_ga_0.clicked.connect(lambda:self.start_algorithm(0, "GA"))
self.start_ga_1.clicked.connect(lambda:self.start_algorithm(1, "GA"))
self.start_ga_2.clicked.connect(lambda:self.start_algorithm(2, "GA"))
self.start_ga_3.clicked.connect(lambda:self.start_algorithm(3, "GA"))
self.start_ga_4.clicked.connect(lambda:self.start_algorithm(4, "GA"))
self.start_ga_5.clicked.connect(lambda:self.start_algorithm(5, "GA"))
self.start_ga_6.clicked.connect(lambda:self.start_algorithm(6, "GA"))
self.start_ga_7.clicked.connect(lambda:self.start_algorithm(7, "GA"))
self.stop_ga_0.clicked.connect(lambda:self.stop_algorithm(0, "GA"))
self.stop_ga_1.clicked.connect(lambda:self.stop_algorithm(1, "GA"))
self.stop_ga_2.clicked.connect(lambda:self.stop_algorithm(2, "GA"))
self.stop_ga_3.clicked.connect(lambda:self.stop_algorithm(3, "GA"))
self.stop_ga_4.clicked.connect(lambda:self.stop_algorithm(4, "GA"))
self.stop_ga_5.clicked.connect(lambda:self.stop_algorithm(5, "GA"))
self.stop_ga_6.clicked.connect(lambda:self.stop_algorithm(6, "GA"))
self.stop_ga_7.clicked.connect(lambda:self.stop_algorithm(7, "GA"))
self.start_de_0.clicked.connect(lambda:self.start_algorithm(0, "DE"))
self.start_de_1.clicked.connect(lambda:self.start_algorithm(1, "DE"))
self.start_de_2.clicked.connect(lambda:self.start_algorithm(2, "DE"))
self.start_de_3.clicked.connect(lambda:self.start_algorithm(3, "DE"))
self.start_de_4.clicked.connect(lambda:self.start_algorithm(4, "DE"))
self.start_de_5.clicked.connect(lambda:self.start_algorithm(5, "DE"))
self.start_de_6.clicked.connect(lambda:self.start_algorithm(6, "DE"))
self.start_de_7.clicked.connect(lambda:self.start_algorithm(7, "DE"))
self.stop_de_0.clicked.connect(lambda:self.stop_algorithm(0, "DE"))
self.stop_de_1.clicked.connect(lambda:self.stop_algorithm(1, "DE"))
self.stop_de_2.clicked.connect(lambda:self.stop_algorithm(2, "DE"))
self.stop_de_3.clicked.connect(lambda:self.stop_algorithm(3, "DE"))
self.stop_de_4.clicked.connect(lambda:self.stop_algorithm(4, "DE"))
self.stop_de_5.clicked.connect(lambda:self.stop_algorithm(5, "DE"))
self.stop_de_6.clicked.connect(lambda:self.stop_algorithm(6, "DE"))
self.stop_de_7.clicked.connect(lambda:self.stop_algorithm(7, "DE"))
# Results
self.process_open_button.clicked.connect(self.handle_button_results)
self.plot_graph_button.clicked.connect(lambda:self.plot_graphics())
self.copy_lag0_pushbutton.clicked.connect(lambda:self.copy_text(0))
self.copy_lag1_pushbutton.clicked.connect(lambda:self.copy_text(1))
self.copy_lag2_pushbutton.clicked.connect(lambda:self.copy_text(2))
self.copy_lag3_pushbutton.clicked.connect(lambda:self.copy_text(3))
self.copy_lag4_pushbutton.clicked.connect(lambda:self.copy_text(4))
self.copy_lag5_pushbutton.clicked.connect(lambda:self.copy_text(5))
self.copy_lag6_pushbutton.clicked.connect(lambda:self.copy_text(6))
self.copy_lag7_pushbutton.clicked.connect(lambda:self.copy_text(7))
def handle_button(self):
'''
Open button optimizations algoritms
'''
fileName, _ = QtWidgets.QFileDialog.getOpenFileName(
self, 'Single File', QtCore.QDir.rootPath(), '*.xlsx')
self.open_file_field.setText(fileName)
self.load_worksheet()
def load_worksheet(self):
'''
Load worksheet
'''
self.label_pso_0.setText("Loading worksheet...")
# parent_conn, child_conn = multiprocessing.Pipe()
# process = LoadWorksheetProcess(
# str(0), child_conn, self)
# process.start()
# process.join()
# self.data = process.recv()
# file_path = self.object.open_file_field.text()
self.type_method()
file_path = self.open_file_field.text()
load = LoadExcelFile(file_path, self.debug_method)
self.data = load.run()
def start_algorithm(self, day_lag, method):
'''
Button that starts simulation
'''
self.type_method()
parent_conn, child_conn = multiprocessing.Pipe()
# pso1_label = Communicator(self.pso1_label)
process = OtimizationProcess(
self.cont_process, child_conn, self, day_lag, method)
process.start()
self.cont_process += 1
# self.label_pso_0.setText(parent_conn.recv())
if method == "PSO":
self.process_pso[day_lag] = process
elif method == "DE":
self.process_de[day_lag] = process
elif method == "GA":
self.process_ga[day_lag] = process
logging.info("Start %s -> lag %d " % (method, day_lag))
def stop_algorithm(self, day_lag, method):
'''
Button that stop simulation
'''
# pso1_label = Communicator(self.pso1_label)
if method == "PSO":
self.process_pso[day_lag].terminate()
elif method == "DE":
self.process_de[day_lag].terminate()
elif method == "GA":
self.process_ga[day_lag].terminate()
logging.info("Stop %s -> lag %d " % (method, day_lag))
def handle_button_results(self):
'''
Open button result
'''
logging.info("Loading json file...")
# file_path, test = QtWidgets.QFileDialog.getOpenFileName(
# self, 'Single File', QtCore.QDir.rootPath(), '*.txt')
mypath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select Folder')
_, _, filenames = next(walk(mypath))
self.graph_file_field.setText(mypath)
self.json_data = list()
for file_ in filenames:
aux_path = mypath + "/" + file_
with open(aux_path, 'rb') as handler:
aux_data = pickle.loads(handler.read())
self.json_data.append(aux_data)
self.json_data.sort(key=lambda x: x["obj"].day_lag, reverse=False)
logging.info("Json file load")
self.results_logs()
def results_logs(self):
'''
Creates the results log in the interface
'''
logging.info("Logging the interface")
my_logs = PlotLogs(self)
my_logs.run()
def plot_graphics(self):
'''
Button that plots Graphics
'''
logging.info("Plotting Graphics")
graphics = PlotGraphics(self)
graphics.run()
def copy_text(self, lag):
'''
copies the generated text to the cliboards
'''
ae = self.json_data[lag]['best'].ae
mse = self.json_data[lag]['best'].mse
mape = self.json_data[lag]['best'].mape
arv = self.json_data[lag]['best'].arv
ia = self.json_data[lag]['best'].ia
mae = self.json_data[lag]['best'].mae
rmse = self.json_data[lag]['best'].rmse
mean = self.json_data[lag]['best'].mean
ranking = self.json_data[lag]['best'].ranking
df=pd.DataFrame(columns = [ ae, mse, mape, arv, ia, mae, rmse, mean, ranking])
df.to_clipboard(index=False)
def type_method(self):
'''
type exec method
'''
if self.exec_method_radiobutton.isChecked():
self.debug_method = False
logging.info("Exec method Type: Execution")
if self.debug_method_radiobutton.isChecked():
self.debug_method = True
logging.info("Exec method Type: Debug")
if __name__ == '__main__':
app = QApplication(sys.argv)
form = App()
form.show()
sys.exit(app.exec_())
| en | 0.513911 | @author: <NAME> https://github.com/diegoscastanho # from lib.create_process import LoadWorksheetProcess # from lib.optimization import SerialExecution # General procedures to show the log Ui class init class # set develop (True) or use method (False) # controller start stop process # Open # Start / STOP buttons # Results Open button optimizations algoritms Load worksheet # parent_conn, child_conn = multiprocessing.Pipe() # process = LoadWorksheetProcess( # str(0), child_conn, self) # process.start() # process.join() # self.data = process.recv() # file_path = self.object.open_file_field.text() Button that starts simulation # pso1_label = Communicator(self.pso1_label) # self.label_pso_0.setText(parent_conn.recv()) Button that stop simulation # pso1_label = Communicator(self.pso1_label) Open button result # file_path, test = QtWidgets.QFileDialog.getOpenFileName( # self, 'Single File', QtCore.QDir.rootPath(), '*.txt') Creates the results log in the interface Button that plots Graphics copies the generated text to the cliboards type exec method | 2.216746 | 2 |
Matplotlib/day_11.py | diazknel/lessons | 0 | 6617063 | <gh_stars>0
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.01, 5.0, 0.01)
s1 = np.sin(2 * np.pi * t)
s2 = np.exp(-t)
s3 = np.sin(4 * np.pi * t)
ax1 = plt.subplot(311)
plt.plot(t, s1)
plt.setp(ax1.get_xticklabels(), fontsize=6)
# share x only
ax2 = plt.subplot(312, sharex=ax1)
plt.plot(t, s2)
# make these tick labels invisible
plt.setp(ax2.get_xticklabels(), visible=False)
# share x and y
ax3 = plt.subplot(313, sharex=ax1, sharey=ax1)
plt.plot(t, s3)
plt.xlim(0.01, 5.0)
plt.show()
| import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.01, 5.0, 0.01)
s1 = np.sin(2 * np.pi * t)
s2 = np.exp(-t)
s3 = np.sin(4 * np.pi * t)
ax1 = plt.subplot(311)
plt.plot(t, s1)
plt.setp(ax1.get_xticklabels(), fontsize=6)
# share x only
ax2 = plt.subplot(312, sharex=ax1)
plt.plot(t, s2)
# make these tick labels invisible
plt.setp(ax2.get_xticklabels(), visible=False)
# share x and y
ax3 = plt.subplot(313, sharex=ax1, sharey=ax1)
plt.plot(t, s3)
plt.xlim(0.01, 5.0)
plt.show() | en | 0.703171 | # share x only # make these tick labels invisible # share x and y | 3.169322 | 3 |
lambda/cloudEndure/first_test.py | Mythridor/aws-scripting | 0 | 6617064 | #! /usr/local/bin/Python3.5
import requests
import json
import sys
API_ENTRY_POINT = 'https://console.cloudendure.com/api/latest/'
HEADERS = {'Content-Type': 'application/json'}
id = {'username': '<username>', 'password': '<password>'}
request = requests.post(API_ENTRY_POINT + 'login', data=json.dumps(id), headers=HEADERS)
print(request.text)
session = {'session': request.cookies["session"]}
project_list = requests.get('https://console.cloudendure.com/api/latest/projects', headers=HEADERS, cookies=session)
print(project_list.text)
#project_id = json.loads(project_list.text)["Items"][0]["id"]
#print(project_id)
create_project = requests.post(API_ENTRY_POINT + 'projects')
print(create_project.text) | #! /usr/local/bin/Python3.5
import requests
import json
import sys
API_ENTRY_POINT = 'https://console.cloudendure.com/api/latest/'
HEADERS = {'Content-Type': 'application/json'}
id = {'username': '<username>', 'password': '<password>'}
request = requests.post(API_ENTRY_POINT + 'login', data=json.dumps(id), headers=HEADERS)
print(request.text)
session = {'session': request.cookies["session"]}
project_list = requests.get('https://console.cloudendure.com/api/latest/projects', headers=HEADERS, cookies=session)
print(project_list.text)
#project_id = json.loads(project_list.text)["Items"][0]["id"]
#print(project_id)
create_project = requests.post(API_ENTRY_POINT + 'projects')
print(create_project.text) | en | 0.582544 | #! /usr/local/bin/Python3.5 #project_id = json.loads(project_list.text)["Items"][0]["id"] #print(project_id) | 3.013905 | 3 |
test/scripts/regtest.py | chengdagong/kdplus | 0 | 6617065 |
import unittest
import target
import pykd
class CpuRegTest( unittest.TestCase ):
def testGetRegName(self):
self.assertNotEqual(None, pykd.getRegisterName(10))
def testGetRegValue(self):
for regIndex in xrange(pykd.getNumberRegisters()):
regName = pykd.getRegisterName(regIndex)
try:
self.assertEqual( pykd.reg(regIndex), pykd.reg(regName) )
except pykd.DbgException:
pass # pass exception unsupported register type
def testSetRegValue(self):
oldVal = pykd.reg(2)
pykd.setReg(2, 10)
self.assertEqual(pykd.reg(2), 10)
pykd.setReg( pykd.getRegisterName(2), oldVal )
self.assertEqual(pykd.reg(2), oldVal )
#def testCtor(self):
# currentcpu = pykd.cpu()
# cpu0 = pykd.cpu(0)
#def testIp(self):
# currentcpu = pykd.cpu()
# self.assertNotEqual( 0, currentcpu.ip )
# self.assertNotEqual( 0, currentcpu.sp )
# self.assertNotEqual( 0, currentcpu.fp )
#def testRegEnum(self):
# for r in pykd.cpu():
# pass
|
import unittest
import target
import pykd
class CpuRegTest( unittest.TestCase ):
def testGetRegName(self):
self.assertNotEqual(None, pykd.getRegisterName(10))
def testGetRegValue(self):
for regIndex in xrange(pykd.getNumberRegisters()):
regName = pykd.getRegisterName(regIndex)
try:
self.assertEqual( pykd.reg(regIndex), pykd.reg(regName) )
except pykd.DbgException:
pass # pass exception unsupported register type
def testSetRegValue(self):
oldVal = pykd.reg(2)
pykd.setReg(2, 10)
self.assertEqual(pykd.reg(2), 10)
pykd.setReg( pykd.getRegisterName(2), oldVal )
self.assertEqual(pykd.reg(2), oldVal )
#def testCtor(self):
# currentcpu = pykd.cpu()
# cpu0 = pykd.cpu(0)
#def testIp(self):
# currentcpu = pykd.cpu()
# self.assertNotEqual( 0, currentcpu.ip )
# self.assertNotEqual( 0, currentcpu.sp )
# self.assertNotEqual( 0, currentcpu.fp )
#def testRegEnum(self):
# for r in pykd.cpu():
# pass
| en | 0.508436 | # pass exception unsupported register type #def testCtor(self): # currentcpu = pykd.cpu() # cpu0 = pykd.cpu(0) #def testIp(self): # currentcpu = pykd.cpu() # self.assertNotEqual( 0, currentcpu.ip ) # self.assertNotEqual( 0, currentcpu.sp ) # self.assertNotEqual( 0, currentcpu.fp ) #def testRegEnum(self): # for r in pykd.cpu(): # pass | 2.604289 | 3 |
third_party/waveshare/epd2in9.py | gpshead/epaper-circuitpython | 14 | 6617066 | <filename>third_party/waveshare/epd2in9.py
# Ported to CircuitPython 3.0 by <NAME>
##
# @filename : epd2in9.py
# @brief : Implements for e-paper library
# @author : <NAME>
#
# Copyright (C) Waveshare September 9 2017
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documnetation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import time
from . import epdif
# EPD2IN9 commands
DRIVER_OUTPUT_CONTROL = 0x01
BOOSTER_SOFT_START_CONTROL = 0x0C
GATE_SCAN_START_POSITION = 0x0F
DEEP_SLEEP_MODE = 0x10
DATA_ENTRY_MODE_SETTING = 0x11
SW_RESET = 0x12
TEMPERATURE_SENSOR_CONTROL = 0x1A
MASTER_ACTIVATION = 0x20
DISPLAY_UPDATE_CONTROL_1 = 0x21
DISPLAY_UPDATE_CONTROL_2 = 0x22
WRITE_RAM = 0x24
WRITE_VCOM_REGISTER = 0x2C
WRITE_LUT_REGISTER = 0x32
SET_DUMMY_LINE_PERIOD = 0x3A
SET_GATE_TIME = 0x3B
BORDER_WAVEFORM_CONTROL = 0x3C
SET_RAM_X_ADDRESS_START_END_POSITION = 0x44
SET_RAM_Y_ADDRESS_START_END_POSITION = 0x45
SET_RAM_X_ADDRESS_COUNTER = 0x4E
SET_RAM_Y_ADDRESS_COUNTER = 0x4F
TERMINATE_FRAME_READ_WRITE = 0xFF
class EPD:
width = 128
height = 296
def __init__(self):
assert not (self.width & 3), "width must be a multiple of 8"
self.reset_pin = None
self.dc_pin = None
self.busy_pin = None
self.lut = self.lut_full_update
# TODO convert to raw bytes literals to save space / mem / import time
lut_full_update = bytes((
0x02, 0x02, 0x01, 0x11, 0x12, 0x12, 0x22, 0x22,
0x66, 0x69, 0x69, 0x59, 0x58, 0x99, 0x99, 0x88,
0x00, 0x00, 0x00, 0x00, 0xF8, 0xB4, 0x13, 0x51,
0x35, 0x51, 0x51, 0x19, 0x01, 0x00
))
lut_partial_update = bytes((
0x10, 0x18, 0x18, 0x08, 0x18, 0x18, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x13, 0x14, 0x44, 0x12,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00
))
def _delay_ms(self, ms):
time.sleep(ms / 1000.)
def _send_command(self, command):
self.dc_pin.value = 0
epdif.spi_transfer(command.to_bytes(1, 'big'))
def _send_data(self, data):
self.dc_pin.value = 1
if isinstance(data, int):
epdif.spi_transfer(data.to_bytes(1, 'big'))
else:
# The EPD needs CS to cycle hi between every byte so we loop doing
# one byte transfers to cause that. Not efficient, but it makes
# it work. Data sheets say needs to be at least a 60ns CS pulse.
for i in range(len(data)):
epdif.spi_transfer(data[i:i+1])
@property
def fb_bytes(self):
return self.width * self.height // 8
def init(self, lut=None):
try:
epdif.epd_io_bus_init()
except RuntimeError:
pass # It avoids global io bus reinitialization. Good.
self.reset_pin = epdif.RST_PIN
self.dc_pin = epdif.DC_PIN
self.busy_pin = epdif.BUSY_PIN
# EPD hardware init start
self.lut = lut or self.lut_full_update
self.reset()
self._send_command(DRIVER_OUTPUT_CONTROL)
self._send_data((self.height - 1) & 0xFF)
self._send_data(((self.height - 1) >> 8) & 0xFF)
self._send_data(0x00) # GD = 0 SM = 0 TB = 0
self._send_command(BOOSTER_SOFT_START_CONTROL)
self._send_data(0xD7)
self._send_data(0xD6)
self._send_data(0x9D)
self._send_command(WRITE_VCOM_REGISTER)
self._send_data(0xA8) # VCOM 7C
self._send_command(SET_DUMMY_LINE_PERIOD)
self._send_data(0x1A) # 4 dummy lines per gate
self._send_command(SET_GATE_TIME)
self._send_data(0x08) # 2us per line
self._send_command(DATA_ENTRY_MODE_SETTING)
self._send_data(0x03) # X increment Y increment
self.set_lut(self.lut)
# EPD hardware init end
def wait_until_idle(self):
while self.busy_pin.value == 1: # 0: idle, 1: busy
self._delay_ms(10)
##
# @brief: module reset.
# often used to awaken the module in deep sleep,
##
def reset(self):
self.reset_pin.value = 0 # module reset
self._delay_ms(200)
self.reset_pin.value = 1
self._delay_ms(200)
##
# @brief: set the look-up table register
##
def set_lut(self, lut=None):
self.lut = lut or self.lut_full_update
assert len(self.lut) == 30 # the length of look-up table is 30 bytes
self._send_command(WRITE_LUT_REGISTER)
self._send_data(self.lut)
##
# @brief: put an image to the frame memory.
# this won't update the display.
##
def set_frame_memory(self, bitmap, x, y):
"""Place bitmap at x (multiple of 8), y in the EPD frame buffer.
bitmap: A MonoBitmap instance; must be a multiple of 8 wide.
"""
if x & 0x7 or bitmap.width & 0x7 or x < 0 or y < 0:
raise ValueError('bad x, y, or width: %d, %d, %d'
% (x, y, bitmap.width))
image_width = bitmap.width
image_height = bitmap.height
if (x + image_width >= self.width):
x_end = self.width - 1
else:
x_end = x + image_width - 1
if (y + image_height >= self.height):
y_end = self.height - 1
else:
y_end = y + image_height - 1
self._set_memory_area(x, y, x_end, y_end)
for j in range(y, y_end + 1):
# The 2.13" display only likes receiving one row of data per WRITE_RAM.
# At a guess: Internally it may be bit based and does this to avoid
# implementing skipping partial end of row bytes given the non
# multiple of 8 width resolution?
self._set_memory_pointer(x, j)
offset = j * self.width // 8
self._send_command(WRITE_RAM)
self._send_data(bitmap.bit_buf[offset+x:offset+(x_end//8)+1])
def clear_frame_memory(self, pattern=0xff):
"""Fill the frame memory with a pattern byte. Does not call update."""
self._set_memory_area(0, 0, self.width - 1, self.height - 1)
self._set_memory_pointer(0, 0)
row = pattern.to_bytes(1, 'big') * ((self.width + 7) // 8)
for j in range(self.height):
# Some displays only accept one row of data per WRITE_RAM.
self._set_memory_pointer(0, j)
self._send_command(WRITE_RAM)
self._send_data(row)
##
# @brief: update the display
# there are 2 memory areas embedded in the e-paper display
# but once this function is called,
# the the next action of SetFrameMemory or ClearFrame will
# set the other memory area.
##
def display_frame(self):
"""Calling this will swap the display for the other buffer."""
self._send_command(DISPLAY_UPDATE_CONTROL_2)
self._send_data(0xC4)
self._send_command(MASTER_ACTIVATION)
self._send_command(TERMINATE_FRAME_READ_WRITE)
self.wait_until_idle()
def display_frame_buf(self, frame_buffer, fast_ghosting=False):
assert len(frame_buffer) == self.fb_bytes
for _ in range(2):
self._set_memory_area(0, 0, self.width-1, self.height-1)
for j in range(0, self.height):
# Some displays only accept one row of data per WRITE_RAM.
self._set_memory_pointer(0, j)
offset = j * self.width // 8
self._send_command(WRITE_RAM)
self._send_data(frame_buffer[offset:offset + (self.width//8) + 1])
self.display_frame()
if fast_ghosting:
break
def display_bitmap(self, bitmap, fast_ghosting=False):
"""Render a MonoBitmap onto the display.
Args:
bitmap: A MonoBitmap instance
fast_ghosting: If true the display update is twice as fast by only
refreshing once; this can leave a ghost of the previous contents.
"""
# TODO: add partial update support.
# if bitmap size is full frame size and x/y offsets are 0:
# epd.init(epd.lut_full_update)
# else:
# epd.init(epd.lut_partial_update)
self.set_frame_memory(bitmap, 0, 0)
self.display_frame()
if not fast_ghosting:
self.set_frame_memory(bitmap, 0, 0)
self.display_frame()
##
# @brief: specify the memory area for data R/W
##
def _set_memory_area(self, x_start, y_start, x_end, y_end):
if x_start & 0x7:
raise ValueError('x must be a multiple of 8 (%d)' % (x_start,))
self._send_command(SET_RAM_X_ADDRESS_START_END_POSITION)
self._send_data((x_start >> 3) & 0xFF)
self._send_data((x_end >> 3) & 0xFF)
self._send_command(SET_RAM_Y_ADDRESS_START_END_POSITION)
self._send_data(y_start & 0xFF)
self._send_data((y_start >> 8) & 0xFF)
self._send_data(y_end & 0xFF)
self._send_data((y_end >> 8) & 0xFF)
##
# @brief: specify the start point for data R/W
##
def _set_memory_pointer(self, x, y):
if x & 0x7:
raise ValueError('x must be a multiple of 8')
self._send_command(SET_RAM_X_ADDRESS_COUNTER)
self._send_data((x >> 3) & 0xFF)
self._send_command(SET_RAM_Y_ADDRESS_COUNTER)
self._send_data(y & 0xFF)
self._send_data((y >> 8) & 0xFF)
self.wait_until_idle()
##
# @brief: After this command is transmitted, the chip would enter the
# deep-sleep mode to save power.
# The deep sleep mode would return to standby by hardware reset.
# You can use reset() to awaken or init() to initialize
##
def sleep(self):
self._send_command(DEEP_SLEEP_MODE)
self.wait_until_idle()
| <filename>third_party/waveshare/epd2in9.py
# Ported to CircuitPython 3.0 by <NAME>
##
# @filename : epd2in9.py
# @brief : Implements for e-paper library
# @author : <NAME>
#
# Copyright (C) Waveshare September 9 2017
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documnetation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import time
from . import epdif
# EPD2IN9 commands
DRIVER_OUTPUT_CONTROL = 0x01
BOOSTER_SOFT_START_CONTROL = 0x0C
GATE_SCAN_START_POSITION = 0x0F
DEEP_SLEEP_MODE = 0x10
DATA_ENTRY_MODE_SETTING = 0x11
SW_RESET = 0x12
TEMPERATURE_SENSOR_CONTROL = 0x1A
MASTER_ACTIVATION = 0x20
DISPLAY_UPDATE_CONTROL_1 = 0x21
DISPLAY_UPDATE_CONTROL_2 = 0x22
WRITE_RAM = 0x24
WRITE_VCOM_REGISTER = 0x2C
WRITE_LUT_REGISTER = 0x32
SET_DUMMY_LINE_PERIOD = 0x3A
SET_GATE_TIME = 0x3B
BORDER_WAVEFORM_CONTROL = 0x3C
SET_RAM_X_ADDRESS_START_END_POSITION = 0x44
SET_RAM_Y_ADDRESS_START_END_POSITION = 0x45
SET_RAM_X_ADDRESS_COUNTER = 0x4E
SET_RAM_Y_ADDRESS_COUNTER = 0x4F
TERMINATE_FRAME_READ_WRITE = 0xFF
class EPD:
width = 128
height = 296
def __init__(self):
assert not (self.width & 3), "width must be a multiple of 8"
self.reset_pin = None
self.dc_pin = None
self.busy_pin = None
self.lut = self.lut_full_update
# TODO convert to raw bytes literals to save space / mem / import time
lut_full_update = bytes((
0x02, 0x02, 0x01, 0x11, 0x12, 0x12, 0x22, 0x22,
0x66, 0x69, 0x69, 0x59, 0x58, 0x99, 0x99, 0x88,
0x00, 0x00, 0x00, 0x00, 0xF8, 0xB4, 0x13, 0x51,
0x35, 0x51, 0x51, 0x19, 0x01, 0x00
))
lut_partial_update = bytes((
0x10, 0x18, 0x18, 0x08, 0x18, 0x18, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x13, 0x14, 0x44, 0x12,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00
))
def _delay_ms(self, ms):
time.sleep(ms / 1000.)
def _send_command(self, command):
self.dc_pin.value = 0
epdif.spi_transfer(command.to_bytes(1, 'big'))
def _send_data(self, data):
self.dc_pin.value = 1
if isinstance(data, int):
epdif.spi_transfer(data.to_bytes(1, 'big'))
else:
# The EPD needs CS to cycle hi between every byte so we loop doing
# one byte transfers to cause that. Not efficient, but it makes
# it work. Data sheets say needs to be at least a 60ns CS pulse.
for i in range(len(data)):
epdif.spi_transfer(data[i:i+1])
@property
def fb_bytes(self):
return self.width * self.height // 8
def init(self, lut=None):
try:
epdif.epd_io_bus_init()
except RuntimeError:
pass # It avoids global io bus reinitialization. Good.
self.reset_pin = epdif.RST_PIN
self.dc_pin = epdif.DC_PIN
self.busy_pin = epdif.BUSY_PIN
# EPD hardware init start
self.lut = lut or self.lut_full_update
self.reset()
self._send_command(DRIVER_OUTPUT_CONTROL)
self._send_data((self.height - 1) & 0xFF)
self._send_data(((self.height - 1) >> 8) & 0xFF)
self._send_data(0x00) # GD = 0 SM = 0 TB = 0
self._send_command(BOOSTER_SOFT_START_CONTROL)
self._send_data(0xD7)
self._send_data(0xD6)
self._send_data(0x9D)
self._send_command(WRITE_VCOM_REGISTER)
self._send_data(0xA8) # VCOM 7C
self._send_command(SET_DUMMY_LINE_PERIOD)
self._send_data(0x1A) # 4 dummy lines per gate
self._send_command(SET_GATE_TIME)
self._send_data(0x08) # 2us per line
self._send_command(DATA_ENTRY_MODE_SETTING)
self._send_data(0x03) # X increment Y increment
self.set_lut(self.lut)
# EPD hardware init end
def wait_until_idle(self):
while self.busy_pin.value == 1: # 0: idle, 1: busy
self._delay_ms(10)
##
# @brief: module reset.
# often used to awaken the module in deep sleep,
##
def reset(self):
self.reset_pin.value = 0 # module reset
self._delay_ms(200)
self.reset_pin.value = 1
self._delay_ms(200)
##
# @brief: set the look-up table register
##
def set_lut(self, lut=None):
self.lut = lut or self.lut_full_update
assert len(self.lut) == 30 # the length of look-up table is 30 bytes
self._send_command(WRITE_LUT_REGISTER)
self._send_data(self.lut)
##
# @brief: put an image to the frame memory.
# this won't update the display.
##
def set_frame_memory(self, bitmap, x, y):
"""Place bitmap at x (multiple of 8), y in the EPD frame buffer.
bitmap: A MonoBitmap instance; must be a multiple of 8 wide.
"""
if x & 0x7 or bitmap.width & 0x7 or x < 0 or y < 0:
raise ValueError('bad x, y, or width: %d, %d, %d'
% (x, y, bitmap.width))
image_width = bitmap.width
image_height = bitmap.height
if (x + image_width >= self.width):
x_end = self.width - 1
else:
x_end = x + image_width - 1
if (y + image_height >= self.height):
y_end = self.height - 1
else:
y_end = y + image_height - 1
self._set_memory_area(x, y, x_end, y_end)
for j in range(y, y_end + 1):
# The 2.13" display only likes receiving one row of data per WRITE_RAM.
# At a guess: Internally it may be bit based and does this to avoid
# implementing skipping partial end of row bytes given the non
# multiple of 8 width resolution?
self._set_memory_pointer(x, j)
offset = j * self.width // 8
self._send_command(WRITE_RAM)
self._send_data(bitmap.bit_buf[offset+x:offset+(x_end//8)+1])
def clear_frame_memory(self, pattern=0xff):
"""Fill the frame memory with a pattern byte. Does not call update."""
self._set_memory_area(0, 0, self.width - 1, self.height - 1)
self._set_memory_pointer(0, 0)
row = pattern.to_bytes(1, 'big') * ((self.width + 7) // 8)
for j in range(self.height):
# Some displays only accept one row of data per WRITE_RAM.
self._set_memory_pointer(0, j)
self._send_command(WRITE_RAM)
self._send_data(row)
##
# @brief: update the display
# there are 2 memory areas embedded in the e-paper display
# but once this function is called,
# the the next action of SetFrameMemory or ClearFrame will
# set the other memory area.
##
def display_frame(self):
"""Calling this will swap the display for the other buffer."""
self._send_command(DISPLAY_UPDATE_CONTROL_2)
self._send_data(0xC4)
self._send_command(MASTER_ACTIVATION)
self._send_command(TERMINATE_FRAME_READ_WRITE)
self.wait_until_idle()
def display_frame_buf(self, frame_buffer, fast_ghosting=False):
assert len(frame_buffer) == self.fb_bytes
for _ in range(2):
self._set_memory_area(0, 0, self.width-1, self.height-1)
for j in range(0, self.height):
# Some displays only accept one row of data per WRITE_RAM.
self._set_memory_pointer(0, j)
offset = j * self.width // 8
self._send_command(WRITE_RAM)
self._send_data(frame_buffer[offset:offset + (self.width//8) + 1])
self.display_frame()
if fast_ghosting:
break
def display_bitmap(self, bitmap, fast_ghosting=False):
"""Render a MonoBitmap onto the display.
Args:
bitmap: A MonoBitmap instance
fast_ghosting: If true the display update is twice as fast by only
refreshing once; this can leave a ghost of the previous contents.
"""
# TODO: add partial update support.
# if bitmap size is full frame size and x/y offsets are 0:
# epd.init(epd.lut_full_update)
# else:
# epd.init(epd.lut_partial_update)
self.set_frame_memory(bitmap, 0, 0)
self.display_frame()
if not fast_ghosting:
self.set_frame_memory(bitmap, 0, 0)
self.display_frame()
##
# @brief: specify the memory area for data R/W
##
def _set_memory_area(self, x_start, y_start, x_end, y_end):
if x_start & 0x7:
raise ValueError('x must be a multiple of 8 (%d)' % (x_start,))
self._send_command(SET_RAM_X_ADDRESS_START_END_POSITION)
self._send_data((x_start >> 3) & 0xFF)
self._send_data((x_end >> 3) & 0xFF)
self._send_command(SET_RAM_Y_ADDRESS_START_END_POSITION)
self._send_data(y_start & 0xFF)
self._send_data((y_start >> 8) & 0xFF)
self._send_data(y_end & 0xFF)
self._send_data((y_end >> 8) & 0xFF)
##
# @brief: specify the start point for data R/W
##
def _set_memory_pointer(self, x, y):
if x & 0x7:
raise ValueError('x must be a multiple of 8')
self._send_command(SET_RAM_X_ADDRESS_COUNTER)
self._send_data((x >> 3) & 0xFF)
self._send_command(SET_RAM_Y_ADDRESS_COUNTER)
self._send_data(y & 0xFF)
self._send_data((y >> 8) & 0xFF)
self.wait_until_idle()
##
# @brief: After this command is transmitted, the chip would enter the
# deep-sleep mode to save power.
# The deep sleep mode would return to standby by hardware reset.
# You can use reset() to awaken or init() to initialize
##
def sleep(self):
self._send_command(DEEP_SLEEP_MODE)
self.wait_until_idle()
| en | 0.752059 | # Ported to CircuitPython 3.0 by <NAME> ## # @filename : epd2in9.py # @brief : Implements for e-paper library # @author : <NAME> # # Copyright (C) Waveshare September 9 2017 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documnetation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # EPD2IN9 commands # TODO convert to raw bytes literals to save space / mem / import time # The EPD needs CS to cycle hi between every byte so we loop doing # one byte transfers to cause that. Not efficient, but it makes # it work. Data sheets say needs to be at least a 60ns CS pulse. # It avoids global io bus reinitialization. Good. # EPD hardware init start # GD = 0 SM = 0 TB = 0 # VCOM 7C # 4 dummy lines per gate # 2us per line # X increment Y increment # EPD hardware init end # 0: idle, 1: busy ## # @brief: module reset. # often used to awaken the module in deep sleep, ## # module reset ## # @brief: set the look-up table register ## # the length of look-up table is 30 bytes ## # @brief: put an image to the frame memory. # this won't update the display. ## Place bitmap at x (multiple of 8), y in the EPD frame buffer. bitmap: A MonoBitmap instance; must be a multiple of 8 wide. # The 2.13" display only likes receiving one row of data per WRITE_RAM. # At a guess: Internally it may be bit based and does this to avoid # implementing skipping partial end of row bytes given the non # multiple of 8 width resolution? Fill the frame memory with a pattern byte. Does not call update. # Some displays only accept one row of data per WRITE_RAM. ## # @brief: update the display # there are 2 memory areas embedded in the e-paper display # but once this function is called, # the the next action of SetFrameMemory or ClearFrame will # set the other memory area. ## Calling this will swap the display for the other buffer. # Some displays only accept one row of data per WRITE_RAM. Render a MonoBitmap onto the display. Args: bitmap: A MonoBitmap instance fast_ghosting: If true the display update is twice as fast by only refreshing once; this can leave a ghost of the previous contents. # TODO: add partial update support. # if bitmap size is full frame size and x/y offsets are 0: # epd.init(epd.lut_full_update) # else: # epd.init(epd.lut_partial_update) ## # @brief: specify the memory area for data R/W ## ## # @brief: specify the start point for data R/W ## ## # @brief: After this command is transmitted, the chip would enter the # deep-sleep mode to save power. # The deep sleep mode would return to standby by hardware reset. # You can use reset() to awaken or init() to initialize ## | 1.676724 | 2 |
src/const.py | akrisrn/u-no | 0 | 6617067 | <reponame>akrisrn/u-no
from enum import Enum
index_url_name = "index"
articles_url_name = "articles"
attachments_url_name = "uploads"
tags_url_name = "tags"
reindex_url_name = "reindex"
# 组成索引的JSON数据所用的键名
index_id_key = "id"
index_parent_key = "parent"
index_title_key = "title"
index_path_key = "path"
index_url_key = "url"
index_date_key = "date"
index_update_key = "update"
index_tags_key = "tags"
index_fixed_key = "fixed"
index_notags_key = "notags"
index_top_key = "top"
index_highlight_key = "highlight"
index_bereferenced_key = "bereferenced"
index_noheader_key = "noheader"
index_nofooter_key = "nofooter"
flag_tag = "tag"
flag_date = "date"
flag_update = "update"
flag_notags = "notags"
flag_fixed = "fixed"
flag_top = "top"
flag_highlight = "highlight"
flag_ignore = "ignore"
flag_unignore = "unignore"
flag_css = "css"
flag_js = "js"
flag_plugin = "plugin"
flag_header = "header"
flag_footer = "footer"
flag_noheader = "noheader"
flag_nofooter = "nofooter"
show_date_format = "%Y-%m-%d"
hash_length = 7
lib_names = [
"vue",
"pace-js",
"pace-js|css",
"mathjax",
"raphael",
"underscore",
"js-sequence-diagrams",
"flowchart.js",
"jquery",
"tablesorter",
"raty-js",
"raty-js|css",
"github-markdown-css",
"@fortawesome/fontawesome-free",
"source-sans-pro",
"source-code-pro",
]
plugin_names = [
"vue", # 1
"pace", # 1
"jquery", # 1
"markdown-style", # 1
"fonts", # 1
"mathjax", # 0
"uml", # 0
"tablesorter", # 1
"raty", # 1
]
| from enum import Enum
index_url_name = "index"
articles_url_name = "articles"
attachments_url_name = "uploads"
tags_url_name = "tags"
reindex_url_name = "reindex"
# 组成索引的JSON数据所用的键名
index_id_key = "id"
index_parent_key = "parent"
index_title_key = "title"
index_path_key = "path"
index_url_key = "url"
index_date_key = "date"
index_update_key = "update"
index_tags_key = "tags"
index_fixed_key = "fixed"
index_notags_key = "notags"
index_top_key = "top"
index_highlight_key = "highlight"
index_bereferenced_key = "bereferenced"
index_noheader_key = "noheader"
index_nofooter_key = "nofooter"
flag_tag = "tag"
flag_date = "date"
flag_update = "update"
flag_notags = "notags"
flag_fixed = "fixed"
flag_top = "top"
flag_highlight = "highlight"
flag_ignore = "ignore"
flag_unignore = "unignore"
flag_css = "css"
flag_js = "js"
flag_plugin = "plugin"
flag_header = "header"
flag_footer = "footer"
flag_noheader = "noheader"
flag_nofooter = "nofooter"
show_date_format = "%Y-%m-%d"
hash_length = 7
lib_names = [
"vue",
"pace-js",
"pace-js|css",
"mathjax",
"raphael",
"underscore",
"js-sequence-diagrams",
"flowchart.js",
"jquery",
"tablesorter",
"raty-js",
"raty-js|css",
"github-markdown-css",
"@fortawesome/fontawesome-free",
"source-sans-pro",
"source-code-pro",
]
plugin_names = [
"vue", # 1
"pace", # 1
"jquery", # 1
"markdown-style", # 1
"fonts", # 1
"mathjax", # 0
"uml", # 0
"tablesorter", # 1
"raty", # 1
] | zh | 0.380804 | # 组成索引的JSON数据所用的键名 # 1 # 1 # 1 # 1 # 1 # 0 # 0 # 1 # 1 | 1.706123 | 2 |
siptrackd_twisted/helpers.py | sii/siptrackd | 0 | 6617068 | import time
import traceback
from twisted.internet import defer
import siptrackdlib.errors
from siptrackd_twisted import errors
from siptrackd_twisted import log
def ascii_to_unicode(string):
"""Convert a string to unicode.
Since strings from xmlrpclib can be either unicode or ascii we need to
convert them to unicode. If the string is already unicode, leave it alone.
"""
if type(string) == str:
return string.decode('ascii')
return string
def error_handler(func):
"""Deal with SiptrackError and it's relatives.
This is just a simple error handling wrapper for the exported xmlrpc
methods. It handles SiptrackError and related errors in a graceful way.
There's really nothing wrong with an exception ending up here.
"""
def handle_errors(*args, **kwargs):
try:
ret = func(*args, **kwargs)
if isinstance(ret, defer.Deferred):
ret.addErrback(_eb_ret)
return ret
except Exception, e:
return _check_exception(e)
return handle_errors
def _eb_ret(error):
return _check_exception(error.value)
def _check_exception(exc):
if isinstance(exc, siptrackdlib.errors.AlreadyExists):
return errors.client_error_exists(exc.__str__())
elif isinstance(exc, errors.InvalidSessionError):
return errors.invalid_session_error()
elif isinstance(exc, errors.InvalidLocationError):
return errors.client_error_invalid_location(exc.__str__())
elif isinstance(exc, errors.InvalidLoginError):
return errors.client_error_login(exc.__str__())
elif isinstance(exc, errors.PermissionDenied):
return errors.permission_denied(exc.__str__())
elif isinstance(exc, siptrackdlib.errors.PermissionDenied):
return errors.permission_denied(exc.__str__())
elif isinstance(exc, siptrackdlib.errors.NonExistent):
return errors.client_error_nexists(exc.__str__())
elif isinstance(exc, siptrackdlib.errors.SiptrackError):
tbmsg = traceback.format_exc()
log.msg(tbmsg)
return errors.generic_error(exc.__str__())
else:
tbmsg = traceback.format_exc()
log.msg(tbmsg)
return errors.generic_error(exc.__str__())
class ValidateSession(object):
def __init__(self, error_handler = True, require_admin = False):
self.error_handler = error_handler
self.require_admin = require_admin
def __call__(self, func):
def wrapped_f(*args, **kwargs):
if len(args) < 2:
raise errors.InvalidSessionError()
func_self = args[0]
session_id = args[1]
session = func_self.session_handler.fetchSession(session_id)
if self.require_admin:
if not session.user or not session.user.user or not \
session.user.user.administrator:
raise errors.PermissionDenied()
session.accessed()
args = (args[0], session) + args[2:]
start = time.time()
if self.error_handler:
try:
print 'Running', func, args[2:], session.user
ret = func(*args, **kwargs)
if isinstance(ret, defer.Deferred):
ret.addErrback(_eb_ret)
except Exception, e:
ret = _check_exception(e)
else:
ret = func(*args, **kwargs)
# print 'ELAPSED:', func, time.time() - start
return ret
return wrapped_f
| import time
import traceback
from twisted.internet import defer
import siptrackdlib.errors
from siptrackd_twisted import errors
from siptrackd_twisted import log
def ascii_to_unicode(string):
"""Convert a string to unicode.
Since strings from xmlrpclib can be either unicode or ascii we need to
convert them to unicode. If the string is already unicode, leave it alone.
"""
if type(string) == str:
return string.decode('ascii')
return string
def error_handler(func):
"""Deal with SiptrackError and it's relatives.
This is just a simple error handling wrapper for the exported xmlrpc
methods. It handles SiptrackError and related errors in a graceful way.
There's really nothing wrong with an exception ending up here.
"""
def handle_errors(*args, **kwargs):
try:
ret = func(*args, **kwargs)
if isinstance(ret, defer.Deferred):
ret.addErrback(_eb_ret)
return ret
except Exception, e:
return _check_exception(e)
return handle_errors
def _eb_ret(error):
return _check_exception(error.value)
def _check_exception(exc):
if isinstance(exc, siptrackdlib.errors.AlreadyExists):
return errors.client_error_exists(exc.__str__())
elif isinstance(exc, errors.InvalidSessionError):
return errors.invalid_session_error()
elif isinstance(exc, errors.InvalidLocationError):
return errors.client_error_invalid_location(exc.__str__())
elif isinstance(exc, errors.InvalidLoginError):
return errors.client_error_login(exc.__str__())
elif isinstance(exc, errors.PermissionDenied):
return errors.permission_denied(exc.__str__())
elif isinstance(exc, siptrackdlib.errors.PermissionDenied):
return errors.permission_denied(exc.__str__())
elif isinstance(exc, siptrackdlib.errors.NonExistent):
return errors.client_error_nexists(exc.__str__())
elif isinstance(exc, siptrackdlib.errors.SiptrackError):
tbmsg = traceback.format_exc()
log.msg(tbmsg)
return errors.generic_error(exc.__str__())
else:
tbmsg = traceback.format_exc()
log.msg(tbmsg)
return errors.generic_error(exc.__str__())
class ValidateSession(object):
def __init__(self, error_handler = True, require_admin = False):
self.error_handler = error_handler
self.require_admin = require_admin
def __call__(self, func):
def wrapped_f(*args, **kwargs):
if len(args) < 2:
raise errors.InvalidSessionError()
func_self = args[0]
session_id = args[1]
session = func_self.session_handler.fetchSession(session_id)
if self.require_admin:
if not session.user or not session.user.user or not \
session.user.user.administrator:
raise errors.PermissionDenied()
session.accessed()
args = (args[0], session) + args[2:]
start = time.time()
if self.error_handler:
try:
print 'Running', func, args[2:], session.user
ret = func(*args, **kwargs)
if isinstance(ret, defer.Deferred):
ret.addErrback(_eb_ret)
except Exception, e:
ret = _check_exception(e)
else:
ret = func(*args, **kwargs)
# print 'ELAPSED:', func, time.time() - start
return ret
return wrapped_f
| en | 0.832913 | Convert a string to unicode. Since strings from xmlrpclib can be either unicode or ascii we need to convert them to unicode. If the string is already unicode, leave it alone. Deal with SiptrackError and it's relatives. This is just a simple error handling wrapper for the exported xmlrpc methods. It handles SiptrackError and related errors in a graceful way. There's really nothing wrong with an exception ending up here. # print 'ELAPSED:', func, time.time() - start | 2.233546 | 2 |
hyperformer/data/tasks.py | acsets/hyperformer_for_mmt | 0 | 6617069 | """Implements different tasks and defines the processors to convert each dataset
to a sequence to sequence format."""
from collections import OrderedDict
import abc
import datasets
import functools
import logging
import numpy as np
import torch
from hyperformer.metrics import metrics
from typing import Callable, Dict, Mapping, List
from .utils import round_stsb_target, compute_task_max_decoding_length
logger = logging.getLogger(__name__)
from datasets import set_caching_enabled
set_caching_enabled(False)
class AbstractTaskDataset(abc.ABC):
"""Defines the abstract class for all the tasks.
name: the name of the task.
task_specific_config: specifies the special configuration needs
to be passed to encoder when decoding each task. Since different
tasks, have different output space, the maximum decoding length
varies based on the tasks.
preprocessor: a processor to convert the given dataset to the sequence
to sequence format.
metrics: specifies the metrics to evaluate the task based on them.
split_to_data_split: since not all the time, different splits of the
datasets are available, we define a mapping from the wanted split
to the existing dataset splits.
small_datasets_without_all_splits: List of strings, defines the name
of all low-resource tasks in which not all train/test/validation
splits are available.
large_data_without_all_splits: List of strings, defines the name of
all high-resource tasks in which not all train/test/validation
splits are available.
"""
name = NotImplemented
task_specific_config: Dict = NotImplemented
preprocessor: Callable = NotImplemented
metrics: List[Callable] = NotImplemented
split_to_data_split: Mapping[str, str] = \
{"train": "train", "validation": "validation", "test": "test"}
small_datasets_without_all_splits = ["cola", "wnli", "rte", "trec", "superglue-cb", "sick",
"mrpc", "stsb", "imdb", "commonsense_qa", "superglue-boolq"]
large_data_without_all_splits = ["yelp_polarity", "qqp", "qnli",
"social_i_qa", "cosmos_qa", "winogrande", "hellaswag", "sst2"]
def __init__(self, seed=42):
self.seed = seed
def get_sampled_split(self, split: int, n_obs: int = None):
# If the requested number of observation is more than dataset
# size we reset it to the maximum available.
split = self.split_to_data_split[split]
dataset = self.load_dataset(split)
total_size = len(dataset)
n_obs = self.check_n_obs(n_obs, total_size)
if n_obs is not None:
split = split + "[:{}]".format(n_obs)
return split
def get_shuffled_sampled_split(self, split: int, n_obs: int = None):
# Defines the random generator.
generator = torch.Generator()
generator.manual_seed(self.seed)
# If the requested number of observation is more than dataset
# size we reset it to the maximum available.
mapped_split = self.split_to_data_split[split]
dataset = self.load_dataset(mapped_split)
# shuffle the dataset and get the random samples.
train_size = len(dataset)
indices = torch.randperm(train_size, generator=generator).tolist()
dataset = self.select_dataset_samples(indices, dataset, n_obs=n_obs)
return dataset
def check_n_obs(self, n_obs, total_size):
if n_obs is not None and n_obs > total_size:
n_obs = total_size
logger.warning("n_obs is set to %s", n_obs)
return n_obs
def select_dataset_samples(self, indices, dataset, n_obs: int = None):
"""
Given a dataset for the split, obtains the sample indices for this split
and returns the subsampled dataset.
:param indices: the selected indices.
:param dataset: dataset corresponding to this split.
:return: subsampled dataset.
"""
n_obs = self.check_n_obs(n_obs, len(indices))
indices = indices[:n_obs] if n_obs is not None else indices
return dataset.select(indices)
def load_dataset(self, split: int): #this will be overrided
return datasets.load_dataset(self.name, split=split, script_version="master")
def get_train_split_indices(self, split):
generator = torch.Generator()
generator.manual_seed(self.seed)
mapped_split = self.split_to_data_split["train"]
dataset = self.load_dataset(mapped_split)
train_size = len(dataset)
indices = torch.randperm(train_size, generator=generator).tolist()
validation_size = 1000
if split == "validation":
return indices[:validation_size]
else:
return indices[validation_size:]
def get_half_validation_indices(self, split):
generator = torch.Generator()
generator.manual_seed(self.seed)
mapped_split = self.split_to_data_split["validation"]
dataset = self.load_dataset(mapped_split)
validation_size = len(dataset)
indices = torch.randperm(validation_size, generator=generator).tolist()
if split == "validation":
return indices[:(validation_size // 2)]
else:
return indices[validation_size // 2:]
def get_dataset(self, split, n_obs=None, add_prefix=True, split_validation_test=False):
if split_validation_test and self.name in self.small_datasets_without_all_splits \
and split != "train":
mapped_split = self.split_to_data_split["validation"]
dataset = self.load_dataset(split=mapped_split)
indices = self.get_half_validation_indices(split)
dataset = self.select_dataset_samples(indices, dataset, n_obs)
elif split_validation_test and self.name in self.large_data_without_all_splits \
and split != "test":
dataset = self.load_dataset(split="train")
indices = self.get_train_split_indices(split)
dataset = self.select_dataset_samples(indices, dataset, n_obs)
else:
if n_obs == -1:
dataset = self.load_dataset(split=split)
else:
# shuffles the data and samples it.
dataset = self.get_shuffled_sampled_split(split, n_obs)
return dataset.map(functools.partial(self.preprocessor, add_prefix=add_prefix),
remove_columns=dataset.column_names)
def seq2seq_format(self, src_strs: List[str], tgt_strs: List[str],
add_prefix: bool = False, prefix: str = None):
src_prefix = self.name if prefix is None else prefix
src_strs = [src_prefix] + src_strs if add_prefix else src_strs
return {"src_texts": ' '.join(src_strs),
"tgt_texts": ' '.join(tgt_strs),
"task": self.name}
class IWSLT2017RONL(AbstractTaskDataset):
name = "iwslt2017-ro-nl"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"ro-nl"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("iwslt2017", 'iwslt2017-ro-nl',
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["ro"]]
tgt_texts = [example['translation']["nl"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate Romanian to Dutch")
class IWSLT2017ENNL(AbstractTaskDataset):
name = "iwslt2017-en-nl"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"en-nl"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("iwslt2017", 'iwslt2017-en-nl',
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["en"]]
tgt_texts = [example['translation']["nl"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate English to Dutch")
class WMT16ENROTaskDataset(AbstractTaskDataset):
name = "wmt16-en-ro"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"ro-en"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("wmt16", self.pair,
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["en"]]
tgt_texts = [example['translation']["ro"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate English to Romanian")
class WMT16ROENTaskDataset(AbstractTaskDataset):
name = "wmt16-ro-en"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"ro-en"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("wmt16", self.pair,
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["ro"]]
tgt_texts = [example['translation']["en"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate Romanian to English")
class WMT16ENCSTaskDataset(AbstractTaskDataset):
name = "wmt16-en-cs"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"cs-en"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("wmt16", self.pair,
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["en"]]
tgt_texts = [example['translation']["cs"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate English to Czech")
class WMT16ENFITaskDataset(AbstractTaskDataset):
name = "wmt16-en-fi"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"fi-en"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("wmt16", self.pair,
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["en"]]
tgt_texts = [example['translation']["fi"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate English to Finnish")
DATA_DIR = '' #put the directory where the data is stored here
class Americasnlp2021DatasetTemplate(AbstractTaskDataset):
task_specific_config = {'max_length': 256, 'num_beams': 6, 'early_stopping': False} #cannot be placed inside __init__
metrics = [metrics.bleu] #cannot be placed inside __init__
def __init__(self, tgt, seed, dev_involve_training):
super().__init__(seed)
# self.task_specific_config = {'max_length': 256, 'num_beams': 6}
self.src = 'es_XX'
self.tgt = tgt
self.lang_pair = f"{self.src}-{self.tgt}"
self.name = f"americasnlp2021-{self.lang_pair}" #object name has to match the keys in TASK_MAPPING dict
self.lang_pair_data_dir = f'{DATA_DIR}/{self.lang_pair}/bilingual_data'
self.dev_involve_training = dev_involve_training
def load_dataset(self, split):
if split == 'train' and self.dev_involve_training == False:
return datasets.load_dataset(path='json', name=self.name, split=split, data_files={'train':f'{self.lang_pair_data_dir}/train-{self.lang_pair}.jsonl'})
elif split == 'train' and self.dev_involve_training == True:
print(f'{self.lang_pair_data_dir}/train+0.9dev-{self.lang_pair}.jsonl')
d = datasets.load_dataset(path='json', name=self.name, split=split, data_files={'train':f'{self.lang_pair_data_dir}/train+0.9dev-{self.lang_pair}.jsonl'})
return d
elif split == 'validation' and self.dev_involve_training == False:
return datasets.load_dataset(path='json', name=self.name, split=split, data_files={'validation':f'{self.lang_pair_data_dir}/dev-{self.lang_pair}.jsonl'})
elif split == 'validation' and self.dev_involve_training == True:
return datasets.load_dataset(path='json', name=self.name, split=split, data_files={'validation':f'{self.lang_pair_data_dir}/0.1dev-{self.lang_pair}.jsonl'})
elif split == 'test':
return datasets.load_dataset(path='json', name=self.name, split=split, data_files = {'test':f'{self.lang_pair_data_dir}/test-{self.lang_pair}.jsonl'})
else:
raise ValueError('No such arguments')
def preprocessor(self, example, add_prefix=True):
try:
src_texts = [example['translation'][self.src]]
tgt_texts = [example['translation'][self.tgt]]
except Exception as e:
print(e)
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix=f"Translate {self.src} to {self.tgt}")
class AmericasNLP2021ESAYMDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'aym_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESBZDDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'bzd_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESCNIDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'cni_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESGNDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'gn_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESHCHDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'hch_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESNAHDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'nah_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESOTODataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'oto_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESQUYDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'quy_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESSHPDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'shp_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESTARDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'tar_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
TASK_MAPPING = OrderedDict([
('americasnlp2021-es_XX-aym_XX', AmericasNLP2021ESAYMDataset),
('americasnlp2021-es_XX-bzd_XX', AmericasNLP2021ESBZDDataset),
('americasnlp2021-es_XX-cni_XX', AmericasNLP2021ESCNIDataset),
('americasnlp2021-es_XX-gn_XX', AmericasNLP2021ESGNDataset),
('americasnlp2021-es_XX-hch_XX', AmericasNLP2021ESHCHDataset),
('americasnlp2021-es_XX-nah_XX', AmericasNLP2021ESNAHDataset),
('americasnlp2021-es_XX-oto_XX', AmericasNLP2021ESOTODataset),
('americasnlp2021-es_XX-quy_XX', AmericasNLP2021ESQUYDataset),
('americasnlp2021-es_XX-shp_XX', AmericasNLP2021ESSHPDataset),
('americasnlp2021-es_XX-tar_XX', AmericasNLP2021ESTARDataset)
]
)
class AutoTask:
@classmethod
def get(self, task_name, seed=42):
if task_name in TASK_MAPPING:
return TASK_MAPPING[task_name](seed)
raise ValueError(
"Unrecognized task {} for AutoTask Model: {}.\n"
"Task name should be one of {}.".format(
", ".join(c for c in TASK_MAPPING.keys())
)
)
| """Implements different tasks and defines the processors to convert each dataset
to a sequence to sequence format."""
from collections import OrderedDict
import abc
import datasets
import functools
import logging
import numpy as np
import torch
from hyperformer.metrics import metrics
from typing import Callable, Dict, Mapping, List
from .utils import round_stsb_target, compute_task_max_decoding_length
logger = logging.getLogger(__name__)
from datasets import set_caching_enabled
set_caching_enabled(False)
class AbstractTaskDataset(abc.ABC):
"""Defines the abstract class for all the tasks.
name: the name of the task.
task_specific_config: specifies the special configuration needs
to be passed to encoder when decoding each task. Since different
tasks, have different output space, the maximum decoding length
varies based on the tasks.
preprocessor: a processor to convert the given dataset to the sequence
to sequence format.
metrics: specifies the metrics to evaluate the task based on them.
split_to_data_split: since not all the time, different splits of the
datasets are available, we define a mapping from the wanted split
to the existing dataset splits.
small_datasets_without_all_splits: List of strings, defines the name
of all low-resource tasks in which not all train/test/validation
splits are available.
large_data_without_all_splits: List of strings, defines the name of
all high-resource tasks in which not all train/test/validation
splits are available.
"""
name = NotImplemented
task_specific_config: Dict = NotImplemented
preprocessor: Callable = NotImplemented
metrics: List[Callable] = NotImplemented
split_to_data_split: Mapping[str, str] = \
{"train": "train", "validation": "validation", "test": "test"}
small_datasets_without_all_splits = ["cola", "wnli", "rte", "trec", "superglue-cb", "sick",
"mrpc", "stsb", "imdb", "commonsense_qa", "superglue-boolq"]
large_data_without_all_splits = ["yelp_polarity", "qqp", "qnli",
"social_i_qa", "cosmos_qa", "winogrande", "hellaswag", "sst2"]
def __init__(self, seed=42):
self.seed = seed
def get_sampled_split(self, split: int, n_obs: int = None):
# If the requested number of observation is more than dataset
# size we reset it to the maximum available.
split = self.split_to_data_split[split]
dataset = self.load_dataset(split)
total_size = len(dataset)
n_obs = self.check_n_obs(n_obs, total_size)
if n_obs is not None:
split = split + "[:{}]".format(n_obs)
return split
def get_shuffled_sampled_split(self, split: int, n_obs: int = None):
# Defines the random generator.
generator = torch.Generator()
generator.manual_seed(self.seed)
# If the requested number of observation is more than dataset
# size we reset it to the maximum available.
mapped_split = self.split_to_data_split[split]
dataset = self.load_dataset(mapped_split)
# shuffle the dataset and get the random samples.
train_size = len(dataset)
indices = torch.randperm(train_size, generator=generator).tolist()
dataset = self.select_dataset_samples(indices, dataset, n_obs=n_obs)
return dataset
def check_n_obs(self, n_obs, total_size):
if n_obs is not None and n_obs > total_size:
n_obs = total_size
logger.warning("n_obs is set to %s", n_obs)
return n_obs
def select_dataset_samples(self, indices, dataset, n_obs: int = None):
"""
Given a dataset for the split, obtains the sample indices for this split
and returns the subsampled dataset.
:param indices: the selected indices.
:param dataset: dataset corresponding to this split.
:return: subsampled dataset.
"""
n_obs = self.check_n_obs(n_obs, len(indices))
indices = indices[:n_obs] if n_obs is not None else indices
return dataset.select(indices)
def load_dataset(self, split: int): #this will be overrided
return datasets.load_dataset(self.name, split=split, script_version="master")
def get_train_split_indices(self, split):
generator = torch.Generator()
generator.manual_seed(self.seed)
mapped_split = self.split_to_data_split["train"]
dataset = self.load_dataset(mapped_split)
train_size = len(dataset)
indices = torch.randperm(train_size, generator=generator).tolist()
validation_size = 1000
if split == "validation":
return indices[:validation_size]
else:
return indices[validation_size:]
def get_half_validation_indices(self, split):
generator = torch.Generator()
generator.manual_seed(self.seed)
mapped_split = self.split_to_data_split["validation"]
dataset = self.load_dataset(mapped_split)
validation_size = len(dataset)
indices = torch.randperm(validation_size, generator=generator).tolist()
if split == "validation":
return indices[:(validation_size // 2)]
else:
return indices[validation_size // 2:]
def get_dataset(self, split, n_obs=None, add_prefix=True, split_validation_test=False):
if split_validation_test and self.name in self.small_datasets_without_all_splits \
and split != "train":
mapped_split = self.split_to_data_split["validation"]
dataset = self.load_dataset(split=mapped_split)
indices = self.get_half_validation_indices(split)
dataset = self.select_dataset_samples(indices, dataset, n_obs)
elif split_validation_test and self.name in self.large_data_without_all_splits \
and split != "test":
dataset = self.load_dataset(split="train")
indices = self.get_train_split_indices(split)
dataset = self.select_dataset_samples(indices, dataset, n_obs)
else:
if n_obs == -1:
dataset = self.load_dataset(split=split)
else:
# shuffles the data and samples it.
dataset = self.get_shuffled_sampled_split(split, n_obs)
return dataset.map(functools.partial(self.preprocessor, add_prefix=add_prefix),
remove_columns=dataset.column_names)
def seq2seq_format(self, src_strs: List[str], tgt_strs: List[str],
add_prefix: bool = False, prefix: str = None):
src_prefix = self.name if prefix is None else prefix
src_strs = [src_prefix] + src_strs if add_prefix else src_strs
return {"src_texts": ' '.join(src_strs),
"tgt_texts": ' '.join(tgt_strs),
"task": self.name}
class IWSLT2017RONL(AbstractTaskDataset):
name = "iwslt2017-ro-nl"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"ro-nl"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("iwslt2017", 'iwslt2017-ro-nl',
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["ro"]]
tgt_texts = [example['translation']["nl"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate Romanian to Dutch")
class IWSLT2017ENNL(AbstractTaskDataset):
name = "iwslt2017-en-nl"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"en-nl"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("iwslt2017", 'iwslt2017-en-nl',
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["en"]]
tgt_texts = [example['translation']["nl"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate English to Dutch")
class WMT16ENROTaskDataset(AbstractTaskDataset):
name = "wmt16-en-ro"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"ro-en"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("wmt16", self.pair,
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["en"]]
tgt_texts = [example['translation']["ro"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate English to Romanian")
class WMT16ROENTaskDataset(AbstractTaskDataset):
name = "wmt16-ro-en"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"ro-en"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("wmt16", self.pair,
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["ro"]]
tgt_texts = [example['translation']["en"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate Romanian to English")
class WMT16ENCSTaskDataset(AbstractTaskDataset):
name = "wmt16-en-cs"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"cs-en"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("wmt16", self.pair,
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["en"]]
tgt_texts = [example['translation']["cs"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate English to Czech")
class WMT16ENFITaskDataset(AbstractTaskDataset):
name = "wmt16-en-fi"
task_specific_config = {'max_length': 300, 'num_beams': 4}
pair = f"fi-en"
metrics = [metrics.bleu]
def load_dataset(self, split):
return datasets.load_dataset("wmt16", self.pair,
split=split, script_version="master")
def preprocessor(self, example, add_prefix=True):
src_texts = [example['translation']["en"]]
tgt_texts = [example['translation']["fi"]]
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix="Translate English to Finnish")
DATA_DIR = '' #put the directory where the data is stored here
class Americasnlp2021DatasetTemplate(AbstractTaskDataset):
task_specific_config = {'max_length': 256, 'num_beams': 6, 'early_stopping': False} #cannot be placed inside __init__
metrics = [metrics.bleu] #cannot be placed inside __init__
def __init__(self, tgt, seed, dev_involve_training):
super().__init__(seed)
# self.task_specific_config = {'max_length': 256, 'num_beams': 6}
self.src = 'es_XX'
self.tgt = tgt
self.lang_pair = f"{self.src}-{self.tgt}"
self.name = f"americasnlp2021-{self.lang_pair}" #object name has to match the keys in TASK_MAPPING dict
self.lang_pair_data_dir = f'{DATA_DIR}/{self.lang_pair}/bilingual_data'
self.dev_involve_training = dev_involve_training
def load_dataset(self, split):
if split == 'train' and self.dev_involve_training == False:
return datasets.load_dataset(path='json', name=self.name, split=split, data_files={'train':f'{self.lang_pair_data_dir}/train-{self.lang_pair}.jsonl'})
elif split == 'train' and self.dev_involve_training == True:
print(f'{self.lang_pair_data_dir}/train+0.9dev-{self.lang_pair}.jsonl')
d = datasets.load_dataset(path='json', name=self.name, split=split, data_files={'train':f'{self.lang_pair_data_dir}/train+0.9dev-{self.lang_pair}.jsonl'})
return d
elif split == 'validation' and self.dev_involve_training == False:
return datasets.load_dataset(path='json', name=self.name, split=split, data_files={'validation':f'{self.lang_pair_data_dir}/dev-{self.lang_pair}.jsonl'})
elif split == 'validation' and self.dev_involve_training == True:
return datasets.load_dataset(path='json', name=self.name, split=split, data_files={'validation':f'{self.lang_pair_data_dir}/0.1dev-{self.lang_pair}.jsonl'})
elif split == 'test':
return datasets.load_dataset(path='json', name=self.name, split=split, data_files = {'test':f'{self.lang_pair_data_dir}/test-{self.lang_pair}.jsonl'})
else:
raise ValueError('No such arguments')
def preprocessor(self, example, add_prefix=True):
try:
src_texts = [example['translation'][self.src]]
tgt_texts = [example['translation'][self.tgt]]
except Exception as e:
print(e)
return self.seq2seq_format(src_texts, tgt_texts, add_prefix,
prefix=f"Translate {self.src} to {self.tgt}")
class AmericasNLP2021ESAYMDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'aym_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESBZDDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'bzd_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESCNIDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'cni_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESGNDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'gn_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESHCHDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'hch_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESNAHDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'nah_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESOTODataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'oto_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESQUYDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'quy_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESSHPDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'shp_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
class AmericasNLP2021ESTARDataset(Americasnlp2021DatasetTemplate):
def __init__(self, seed):
tgt = 'tar_XX'
dev_involve_training = True
super().__init__(tgt, seed, dev_involve_training)
TASK_MAPPING = OrderedDict([
('americasnlp2021-es_XX-aym_XX', AmericasNLP2021ESAYMDataset),
('americasnlp2021-es_XX-bzd_XX', AmericasNLP2021ESBZDDataset),
('americasnlp2021-es_XX-cni_XX', AmericasNLP2021ESCNIDataset),
('americasnlp2021-es_XX-gn_XX', AmericasNLP2021ESGNDataset),
('americasnlp2021-es_XX-hch_XX', AmericasNLP2021ESHCHDataset),
('americasnlp2021-es_XX-nah_XX', AmericasNLP2021ESNAHDataset),
('americasnlp2021-es_XX-oto_XX', AmericasNLP2021ESOTODataset),
('americasnlp2021-es_XX-quy_XX', AmericasNLP2021ESQUYDataset),
('americasnlp2021-es_XX-shp_XX', AmericasNLP2021ESSHPDataset),
('americasnlp2021-es_XX-tar_XX', AmericasNLP2021ESTARDataset)
]
)
class AutoTask:
@classmethod
def get(self, task_name, seed=42):
if task_name in TASK_MAPPING:
return TASK_MAPPING[task_name](seed)
raise ValueError(
"Unrecognized task {} for AutoTask Model: {}.\n"
"Task name should be one of {}.".format(
", ".join(c for c in TASK_MAPPING.keys())
)
)
| en | 0.762674 | Implements different tasks and defines the processors to convert each dataset to a sequence to sequence format. Defines the abstract class for all the tasks. name: the name of the task. task_specific_config: specifies the special configuration needs to be passed to encoder when decoding each task. Since different tasks, have different output space, the maximum decoding length varies based on the tasks. preprocessor: a processor to convert the given dataset to the sequence to sequence format. metrics: specifies the metrics to evaluate the task based on them. split_to_data_split: since not all the time, different splits of the datasets are available, we define a mapping from the wanted split to the existing dataset splits. small_datasets_without_all_splits: List of strings, defines the name of all low-resource tasks in which not all train/test/validation splits are available. large_data_without_all_splits: List of strings, defines the name of all high-resource tasks in which not all train/test/validation splits are available. # If the requested number of observation is more than dataset # size we reset it to the maximum available. # Defines the random generator. # If the requested number of observation is more than dataset # size we reset it to the maximum available. # shuffle the dataset and get the random samples. Given a dataset for the split, obtains the sample indices for this split and returns the subsampled dataset. :param indices: the selected indices. :param dataset: dataset corresponding to this split. :return: subsampled dataset. #this will be overrided # shuffles the data and samples it. #put the directory where the data is stored here #cannot be placed inside __init__ #cannot be placed inside __init__ # self.task_specific_config = {'max_length': 256, 'num_beams': 6} #object name has to match the keys in TASK_MAPPING dict | 2.74484 | 3 |
seimas/migrations/0022_auto_20180816_1903.py | zinaukarenku/zkr-platform | 2 | 6617070 | <filename>seimas/migrations/0022_auto_20180816_1903.py<gh_stars>1-10
# Generated by Django 2.1 on 2018-08-16 19:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('seimas', '0021_politiciangame'),
]
operations = [
migrations.AlterModelOptions(
name='politiciangame',
options={'ordering': ['-created_at'], 'verbose_name_plural': 'Politicians game'},
),
]
| <filename>seimas/migrations/0022_auto_20180816_1903.py<gh_stars>1-10
# Generated by Django 2.1 on 2018-08-16 19:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('seimas', '0021_politiciangame'),
]
operations = [
migrations.AlterModelOptions(
name='politiciangame',
options={'ordering': ['-created_at'], 'verbose_name_plural': 'Politicians game'},
),
]
| en | 0.66651 | # Generated by Django 2.1 on 2018-08-16 19:03 | 1.439898 | 1 |
setup.py | lzoubek/uberforeman | 1 | 6617071 | <filename>setup.py
import sys
import os
VERSION = '1.2.2'
py_vers_tag = '-%s.%s' % sys.version_info[:2]
try:
from setuptools import setup
from setuptools import find_packages
addl_args = dict(
zip_safe = False,
packages = find_packages(),
entry_points = {
'console_scripts': [
'uberforeman = uberforeman:main',
'uberforeman%s = uberforeman:main' % py_vers_tag,
],
},
)
except ImportError:
from distutils.core import setup
addl_args = dict(
packages = ['uberforeman'],
scripts = ['bin/uberforeman'],
)
setup(
name = 'uberforeman',
version = VERSION,
author = '<NAME>',
author_email = '<EMAIL>',
description = ('uberforeman is a CLI tool to foreman that can manage and deploy multi-host setups'),
long_description = \
"""
tbd...
""",
license = 'Apache License 2.0',
keywords = 'foreman automation',
url = 'http://github.com/lzoubek/uberforeman',
install_requires=['requests>=1.2.0'],
data_files = [],
package_data = {'': ['*.txt',
'examples/*.py',
'examples/*/*.py']},
classifiers = [
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
**addl_args
)
| <filename>setup.py
import sys
import os
VERSION = '1.2.2'
py_vers_tag = '-%s.%s' % sys.version_info[:2]
try:
from setuptools import setup
from setuptools import find_packages
addl_args = dict(
zip_safe = False,
packages = find_packages(),
entry_points = {
'console_scripts': [
'uberforeman = uberforeman:main',
'uberforeman%s = uberforeman:main' % py_vers_tag,
],
},
)
except ImportError:
from distutils.core import setup
addl_args = dict(
packages = ['uberforeman'],
scripts = ['bin/uberforeman'],
)
setup(
name = 'uberforeman',
version = VERSION,
author = '<NAME>',
author_email = '<EMAIL>',
description = ('uberforeman is a CLI tool to foreman that can manage and deploy multi-host setups'),
long_description = \
"""
tbd...
""",
license = 'Apache License 2.0',
keywords = 'foreman automation',
url = 'http://github.com/lzoubek/uberforeman',
install_requires=['requests>=1.2.0'],
data_files = [],
package_data = {'': ['*.txt',
'examples/*.py',
'examples/*/*.py']},
classifiers = [
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
**addl_args
)
| none | 1 | 1.503279 | 2 | |
tap_yotpo/streams.py | fishtown-analytics/tap-yotpo | 1 | 6617072 | <filename>tap_yotpo/streams.py<gh_stars>1-10
import singer
from singer import metrics, transform
import pendulum
LOGGER = singer.get_logger()
PAGE_SIZE = 100
EMAILS_PAGE_SIZE = 1000
EMAILS_LOOKBACK_DAYS = 30
REVIEWS_LOOKBACK_DAYS = 30
class Stream(object):
def __init__(self, tap_stream_id, pk_fields, path,
returns_collection=True,
collection_key=None,
pluck_results=False,
custom_formatter=None,
version=None):
self.tap_stream_id = tap_stream_id
self.pk_fields = pk_fields
self.path = path
self.returns_collection = returns_collection
self.collection_key = collection_key
self.pluck_results = pluck_results
self.custom_formatter = custom_formatter or (lambda x: x)
self.version = version
self.start_date = None
def get_start_date(self, ctx, key):
if not self.start_date:
self.start_date = ctx.get_bookmark([self.tap_stream_id, key])
return self.start_date
def metrics(self, records):
with metrics.record_counter(self.tap_stream_id) as counter:
counter.increment(len(records))
def write_records(self, records):
singer.write_records(self.tap_stream_id, records)
self.metrics(records)
def format_response(self, response):
if self.pluck_results:
response = response['response']
if self.returns_collection:
if self.collection_key:
records = (response or {}).get(self.collection_key, [])
else:
records = response or []
else:
records = [] if not response else [response]
return self.custom_formatter(records)
class Paginated(Stream):
def get_params(self, ctx, page):
return {
"count": PAGE_SIZE,
"page": page
}
def on_batch_complete(self, ctx, records, product_id=None):
self.write_records(records)
return True
def _sync(self, ctx, path=None, product_id=None):
if path is None:
path = self.path
if product_id:
bookmark_name = 'product_{}.since_date'.format(product_id)
else:
bookmark_name = 'since_date'
ctx.update_start_date_bookmark([self.tap_stream_id, bookmark_name])
schema = ctx.catalog.get_stream(self.tap_stream_id).schema.to_dict()
page = 1
while True:
params = self.get_params(ctx, page)
opts = {"path": path, "params": params}
resp = ctx.client.GET(self.version, opts, self.tap_stream_id)
raw_records = self.format_response(resp)
records = [transform(record, schema) for record in raw_records]
if not self.on_batch_complete(ctx, records, product_id):
break
if len(records) == 0:
break
page += 1
def sync(self, ctx):
self._sync(ctx)
def _transform_dt(self, time_str):
return pendulum.parse(time_str).in_timezone("UTC")
def update_bookmark(self, ctx, max_record_ts, path_key):
path = [self.tap_stream_id, path_key]
bookmark_ts = self._transform_dt(ctx.get_bookmark(path))
last_record_ts = self._transform_dt(max_record_ts)
if last_record_ts > bookmark_ts:
ctx.set_bookmark(path, last_record_ts.to_date_string())
class Products(Paginated):
def on_batch_complete(self, ctx, records, product_id=None):
ctx.cache["products"].extend(records)
return True
def sync(self, ctx):
self.write_records(ctx.cache["products"])
def fetch_into_cache(self, ctx):
ctx.cache["products"] = []
self._sync(ctx)
class Reviews(Paginated):
def get_params(self, ctx, page):
since_date_raw = self.get_start_date(ctx, 'since_date')
lookback_days = ctx.config.get('reviews_lookback_days',
REVIEWS_LOOKBACK_DAYS)
since_date = pendulum.parse(since_date_raw) \
.in_timezone("UTC") \
.add(days=-lookback_days)
return {
"count": PAGE_SIZE,
"page": page,
"since_date": since_date.to_iso8601_string(),
"deleted": "true"
}
def on_batch_complete(self, ctx, records, product_id=None):
self.write_records(records)
if len(records) == 0:
return False
last_record = records[-1]
max_record_ts = last_record['created_at']
self.update_bookmark(ctx, max_record_ts, 'since_date')
return True
class Emails(Paginated):
def get_params(self, ctx, page):
since_date_raw = self.get_start_date(ctx, 'since_date')
lookback_days = ctx.config.get('email_stats_lookback_days',
EMAILS_LOOKBACK_DAYS)
since_date = pendulum.parse(since_date_raw) \
.in_timezone("UTC") \
.add(days=-lookback_days)
until_date = pendulum.tomorrow().in_timezone("UTC")
return {
"per_page": EMAILS_PAGE_SIZE,
"page": page,
"since": since_date.to_date_string(),
"until": until_date.to_date_string(),
"sort": "ascending"
}
def on_batch_complete(self, ctx, records, product_id=None):
self.write_records(records)
if len(records) == 0:
return False
last_record = records[-1]
max_record_ts = last_record['email_sent_timestamp']
self.update_bookmark(ctx, max_record_ts, 'since_date')
return True
class ProductReviews(Paginated):
def get_params(self, ctx, page):
# This endpoint does not support date filtering
# Start at the beginning of time, and only sync
# records that are more recent than our bookmark
return {
"per_page": PAGE_SIZE,
"page": page,
"sort": ["date", "time"],
"direction": "asc"
}
def sync(self, ctx):
for product in ctx.cache['products']:
product_id = product['external_product_id']
path = self.path.format(product_id=product_id)
self._sync(ctx, path, product_id=product_id)
def on_batch_complete(self, ctx, records, product_id=None):
if len(records) == 0:
return False
bookmark_name = 'product_{}.since_date'.format(product_id)
offset = ctx.get_bookmark([self.tap_stream_id, bookmark_name])
current_bookmark = pendulum.parse(offset).in_timezone("UTC")
last_record = records[-1]
max_record_ts = pendulum.parse(last_record['created_at'])
# if latest in batch is more recent than the current bookmark,
# update the bookmark and write out the record
if max_record_ts >= current_bookmark:
self.write_records(records)
self.update_bookmark(ctx, max_record_ts.to_date_string(),
bookmark_name)
LOGGER.info("Sending batch. Max Record {} is >= bookmark "
"{}".format(max_record_ts, current_bookmark))
else:
LOGGER.info("Skipping batch. Max Record {} is less than bookmark "
"{}".format(max_record_ts, current_bookmark))
return True
products = Products(
"products",
["id"],
"apps/:api_key/products?utoken=:token",
collection_key='products',
version='v1'
)
all_streams = [
products,
Paginated(
"unsubscribers",
["id"],
"apps/:api_key/unsubscribers?utoken=:token",
collection_key='unsubscribers',
pluck_results=True
),
Reviews(
"reviews",
["id"],
"apps/:api_key/reviews?utoken=:token",
collection_key="reviews",
version='v1'
),
Emails(
"emails",
["email_address", "email_sent_timestamp"],
"analytics/v1/emails/:api_key/export/raw_data?token=:token",
collection_key="records"
),
ProductReviews(
"product_reviews",
["id"],
"widget/:api_key/products/{product_id}/reviews.json",
collection_key="reviews",
version='v1',
pluck_results=True
)
]
all_stream_ids = [s.tap_stream_id for s in all_streams]
| <filename>tap_yotpo/streams.py<gh_stars>1-10
import singer
from singer import metrics, transform
import pendulum
LOGGER = singer.get_logger()
PAGE_SIZE = 100
EMAILS_PAGE_SIZE = 1000
EMAILS_LOOKBACK_DAYS = 30
REVIEWS_LOOKBACK_DAYS = 30
class Stream(object):
def __init__(self, tap_stream_id, pk_fields, path,
returns_collection=True,
collection_key=None,
pluck_results=False,
custom_formatter=None,
version=None):
self.tap_stream_id = tap_stream_id
self.pk_fields = pk_fields
self.path = path
self.returns_collection = returns_collection
self.collection_key = collection_key
self.pluck_results = pluck_results
self.custom_formatter = custom_formatter or (lambda x: x)
self.version = version
self.start_date = None
def get_start_date(self, ctx, key):
if not self.start_date:
self.start_date = ctx.get_bookmark([self.tap_stream_id, key])
return self.start_date
def metrics(self, records):
with metrics.record_counter(self.tap_stream_id) as counter:
counter.increment(len(records))
def write_records(self, records):
singer.write_records(self.tap_stream_id, records)
self.metrics(records)
def format_response(self, response):
if self.pluck_results:
response = response['response']
if self.returns_collection:
if self.collection_key:
records = (response or {}).get(self.collection_key, [])
else:
records = response or []
else:
records = [] if not response else [response]
return self.custom_formatter(records)
class Paginated(Stream):
def get_params(self, ctx, page):
return {
"count": PAGE_SIZE,
"page": page
}
def on_batch_complete(self, ctx, records, product_id=None):
self.write_records(records)
return True
def _sync(self, ctx, path=None, product_id=None):
if path is None:
path = self.path
if product_id:
bookmark_name = 'product_{}.since_date'.format(product_id)
else:
bookmark_name = 'since_date'
ctx.update_start_date_bookmark([self.tap_stream_id, bookmark_name])
schema = ctx.catalog.get_stream(self.tap_stream_id).schema.to_dict()
page = 1
while True:
params = self.get_params(ctx, page)
opts = {"path": path, "params": params}
resp = ctx.client.GET(self.version, opts, self.tap_stream_id)
raw_records = self.format_response(resp)
records = [transform(record, schema) for record in raw_records]
if not self.on_batch_complete(ctx, records, product_id):
break
if len(records) == 0:
break
page += 1
def sync(self, ctx):
self._sync(ctx)
def _transform_dt(self, time_str):
return pendulum.parse(time_str).in_timezone("UTC")
def update_bookmark(self, ctx, max_record_ts, path_key):
path = [self.tap_stream_id, path_key]
bookmark_ts = self._transform_dt(ctx.get_bookmark(path))
last_record_ts = self._transform_dt(max_record_ts)
if last_record_ts > bookmark_ts:
ctx.set_bookmark(path, last_record_ts.to_date_string())
class Products(Paginated):
def on_batch_complete(self, ctx, records, product_id=None):
ctx.cache["products"].extend(records)
return True
def sync(self, ctx):
self.write_records(ctx.cache["products"])
def fetch_into_cache(self, ctx):
ctx.cache["products"] = []
self._sync(ctx)
class Reviews(Paginated):
def get_params(self, ctx, page):
since_date_raw = self.get_start_date(ctx, 'since_date')
lookback_days = ctx.config.get('reviews_lookback_days',
REVIEWS_LOOKBACK_DAYS)
since_date = pendulum.parse(since_date_raw) \
.in_timezone("UTC") \
.add(days=-lookback_days)
return {
"count": PAGE_SIZE,
"page": page,
"since_date": since_date.to_iso8601_string(),
"deleted": "true"
}
def on_batch_complete(self, ctx, records, product_id=None):
self.write_records(records)
if len(records) == 0:
return False
last_record = records[-1]
max_record_ts = last_record['created_at']
self.update_bookmark(ctx, max_record_ts, 'since_date')
return True
class Emails(Paginated):
def get_params(self, ctx, page):
since_date_raw = self.get_start_date(ctx, 'since_date')
lookback_days = ctx.config.get('email_stats_lookback_days',
EMAILS_LOOKBACK_DAYS)
since_date = pendulum.parse(since_date_raw) \
.in_timezone("UTC") \
.add(days=-lookback_days)
until_date = pendulum.tomorrow().in_timezone("UTC")
return {
"per_page": EMAILS_PAGE_SIZE,
"page": page,
"since": since_date.to_date_string(),
"until": until_date.to_date_string(),
"sort": "ascending"
}
def on_batch_complete(self, ctx, records, product_id=None):
self.write_records(records)
if len(records) == 0:
return False
last_record = records[-1]
max_record_ts = last_record['email_sent_timestamp']
self.update_bookmark(ctx, max_record_ts, 'since_date')
return True
class ProductReviews(Paginated):
def get_params(self, ctx, page):
# This endpoint does not support date filtering
# Start at the beginning of time, and only sync
# records that are more recent than our bookmark
return {
"per_page": PAGE_SIZE,
"page": page,
"sort": ["date", "time"],
"direction": "asc"
}
def sync(self, ctx):
for product in ctx.cache['products']:
product_id = product['external_product_id']
path = self.path.format(product_id=product_id)
self._sync(ctx, path, product_id=product_id)
def on_batch_complete(self, ctx, records, product_id=None):
if len(records) == 0:
return False
bookmark_name = 'product_{}.since_date'.format(product_id)
offset = ctx.get_bookmark([self.tap_stream_id, bookmark_name])
current_bookmark = pendulum.parse(offset).in_timezone("UTC")
last_record = records[-1]
max_record_ts = pendulum.parse(last_record['created_at'])
# if latest in batch is more recent than the current bookmark,
# update the bookmark and write out the record
if max_record_ts >= current_bookmark:
self.write_records(records)
self.update_bookmark(ctx, max_record_ts.to_date_string(),
bookmark_name)
LOGGER.info("Sending batch. Max Record {} is >= bookmark "
"{}".format(max_record_ts, current_bookmark))
else:
LOGGER.info("Skipping batch. Max Record {} is less than bookmark "
"{}".format(max_record_ts, current_bookmark))
return True
products = Products(
"products",
["id"],
"apps/:api_key/products?utoken=:token",
collection_key='products',
version='v1'
)
all_streams = [
products,
Paginated(
"unsubscribers",
["id"],
"apps/:api_key/unsubscribers?utoken=:token",
collection_key='unsubscribers',
pluck_results=True
),
Reviews(
"reviews",
["id"],
"apps/:api_key/reviews?utoken=:token",
collection_key="reviews",
version='v1'
),
Emails(
"emails",
["email_address", "email_sent_timestamp"],
"analytics/v1/emails/:api_key/export/raw_data?token=:token",
collection_key="records"
),
ProductReviews(
"product_reviews",
["id"],
"widget/:api_key/products/{product_id}/reviews.json",
collection_key="reviews",
version='v1',
pluck_results=True
)
]
all_stream_ids = [s.tap_stream_id for s in all_streams]
| en | 0.904602 | # This endpoint does not support date filtering # Start at the beginning of time, and only sync # records that are more recent than our bookmark # if latest in batch is more recent than the current bookmark, # update the bookmark and write out the record | 2.425633 | 2 |
letterCombinations.py | couyang24/Leetcode_way2master | 0 | 6617073 | <reponame>couyang24/Leetcode_way2master
from itertools import product
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if digits == "":
return []
dct ={
'2':'abc',
'3':'def',
'4':'ghi',
'5':'jkl',
'6':'mno',
'7':'pqrs',
'8':'tuv',
'9':'wxyz'
}
result = []
lst = [[j for j in dct[i]] for i in digits]
return ["".join(i) for i in list(product(*lst))]
| from itertools import product
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if digits == "":
return []
dct ={
'2':'abc',
'3':'def',
'4':'ghi',
'5':'jkl',
'6':'mno',
'7':'pqrs',
'8':'tuv',
'9':'wxyz'
}
result = []
lst = [[j for j in dct[i]] for i in digits]
return ["".join(i) for i in list(product(*lst))] | none | 1 | 3.156904 | 3 | |
videos/077_metaclasses_in_python/passing_kwargs_to_metaclass.py | matthewstidham/VideosSampleCode | 285 | 6617074 | class VerboseMeta(type):
def __new__(mcs, name, bases, namespace, print_f, **kwargs):
print('VerboseMeta new', mcs, name, bases, namespace, print_f, kwargs)
return super().__new__(mcs, name, bases, namespace, **kwargs)
class A(metaclass=VerboseMeta, print_f=print):
pass
def main():
pass
if __name__ == '__main__':
main()
| class VerboseMeta(type):
def __new__(mcs, name, bases, namespace, print_f, **kwargs):
print('VerboseMeta new', mcs, name, bases, namespace, print_f, kwargs)
return super().__new__(mcs, name, bases, namespace, **kwargs)
class A(metaclass=VerboseMeta, print_f=print):
pass
def main():
pass
if __name__ == '__main__':
main()
| none | 1 | 2.955271 | 3 | |
angr/procedures/uclibc/__init__.py | Kyle-Kyle/angr | 6,132 | 6617075 | <reponame>Kyle-Kyle/angr
"""
These procedures implement internal functions in the uClibc libc implementation
"""
| """
These procedures implement internal functions in the uClibc libc implementation
""" | en | 0.639508 | These procedures implement internal functions in the uClibc libc implementation | 1.143734 | 1 |
app/python/src/scalrpy/util/snmp.py | fred-liu/scalr | 1 | 6617076 | import netsnmp
import logging
LOG = logging.getLogger('ScalrPy')
OIDS = {
'cpu': {
'user': '.1.3.6.1.4.1.2021.11.50.0',
'nice': '.1.3.6.1.4.1.2021.11.51.0',
'system': '.1.3.6.1.4.1.2021.11.52.0',
'idle': '.1.3.6.1.4.1.2021.11.53.0',
},
'la': {
'la1': '.1.3.6.1.4.1.2021.10.1.3.1',
'la5': '.1.3.6.1.4.1.2021.10.1.3.2',
'la15': '.1.3.6.1.4.1.2021.10.1.3.3',
},
'mem': {
'swap': '.1.3.6.1.4.1.2021.4.3.0',
'swapavail': '.1.3.6.1.4.1.2021.4.4.0',
'total': '.1.3.6.1.4.1.2021.4.5.0',
'avail': '.1.3.6.1.4.1.2021.4.6.0',
'free': '.1.3.6.1.4.1.2021.4.11.0',
'shared': '.1.3.6.1.4.1.2021.4.13.0',
'buffer': '.1.3.6.1.4.1.2021.4.14.0',
'cached': '.1.3.6.1.4.1.2021.4.15.0',
},
'net': {
'in': '.1.3.6.1.2.1.2.2.1.10.2',
'out': '.1.3.6.1.2.1.2.2.1.16.2',
},
}
def get_metrics(host, port, community, metrics):
assert host, 'host'
assert port, 'port'
assert community, 'community'
assert metrics, 'metrics'
oids = []
for k, v in OIDS.iteritems():
if k in metrics:
for kk, vv in v.iteritems():
oids.append(vv)
if not oids:
return dict()
session = netsnmp.Session(
DestHost='%s:%s' % (host, port),
Version=1,
Community=community,
Timeout=2500000)
Vars = netsnmp.VarList(*oids)
snmp_data = dict((o, v) for o, v in zip(oids, session.get(Vars)))
data = dict()
for metric_name in metrics:
if metric_name not in OIDS:
continue
for metric in OIDS[metric_name].keys():
try:
value = float(snmp_data[OIDS[metric_name][metric]])
except:
value = None
data.setdefault(metric_name, {}).setdefault(metric, value)
return data
| import netsnmp
import logging
LOG = logging.getLogger('ScalrPy')
OIDS = {
'cpu': {
'user': '.1.3.6.1.4.1.2021.11.50.0',
'nice': '.1.3.6.1.4.1.2021.11.51.0',
'system': '.1.3.6.1.4.1.2021.11.52.0',
'idle': '.1.3.6.1.4.1.2021.11.53.0',
},
'la': {
'la1': '.1.3.6.1.4.1.2021.10.1.3.1',
'la5': '.1.3.6.1.4.1.2021.10.1.3.2',
'la15': '.1.3.6.1.4.1.2021.10.1.3.3',
},
'mem': {
'swap': '.1.3.6.1.4.1.2021.4.3.0',
'swapavail': '.1.3.6.1.4.1.2021.4.4.0',
'total': '.1.3.6.1.4.1.2021.4.5.0',
'avail': '.1.3.6.1.4.1.2021.4.6.0',
'free': '.1.3.6.1.4.1.2021.4.11.0',
'shared': '.1.3.6.1.4.1.2021.4.13.0',
'buffer': '.1.3.6.1.4.1.2021.4.14.0',
'cached': '.1.3.6.1.4.1.2021.4.15.0',
},
'net': {
'in': '.1.3.6.1.2.1.2.2.1.10.2',
'out': '.1.3.6.1.2.1.2.2.1.16.2',
},
}
def get_metrics(host, port, community, metrics):
assert host, 'host'
assert port, 'port'
assert community, 'community'
assert metrics, 'metrics'
oids = []
for k, v in OIDS.iteritems():
if k in metrics:
for kk, vv in v.iteritems():
oids.append(vv)
if not oids:
return dict()
session = netsnmp.Session(
DestHost='%s:%s' % (host, port),
Version=1,
Community=community,
Timeout=2500000)
Vars = netsnmp.VarList(*oids)
snmp_data = dict((o, v) for o, v in zip(oids, session.get(Vars)))
data = dict()
for metric_name in metrics:
if metric_name not in OIDS:
continue
for metric in OIDS[metric_name].keys():
try:
value = float(snmp_data[OIDS[metric_name][metric]])
except:
value = None
data.setdefault(metric_name, {}).setdefault(metric, value)
return data
| none | 1 | 1.963859 | 2 | |
gridinit.py | iitd-plos/grid | 0 | 6617077 | <filename>gridinit.py
#!/usr/bin/python
from celery import Celery
from celery.task.control import discard_all
from queuelib import FifoDiskQueue
from config_host import *
import Queue
import datetime
import os
import shelve
import pickle
if __name__ == "__main__":
#discard_all()
print "init called"
counter_state = shelve.open(build_dir + "/counter_state")
counter_state['counter'] = 1
counter_state.close()
print "counter_state inited"
workq_state = shelve.open(build_dir + "/workq_state")
workq_state['workq'] = []
workq_state.close()
print "workq state inited"
readyq = FifoDiskQueue(build_dir + "/readyq")
readyq.close()
del readyq
print "readyq inited"
doneq = FifoDiskQueue(build_dir + "/doneq")
doneq.close()
del doneq
print "doneq inited"
print "init done"
| <filename>gridinit.py
#!/usr/bin/python
from celery import Celery
from celery.task.control import discard_all
from queuelib import FifoDiskQueue
from config_host import *
import Queue
import datetime
import os
import shelve
import pickle
if __name__ == "__main__":
#discard_all()
print "init called"
counter_state = shelve.open(build_dir + "/counter_state")
counter_state['counter'] = 1
counter_state.close()
print "counter_state inited"
workq_state = shelve.open(build_dir + "/workq_state")
workq_state['workq'] = []
workq_state.close()
print "workq state inited"
readyq = FifoDiskQueue(build_dir + "/readyq")
readyq.close()
del readyq
print "readyq inited"
doneq = FifoDiskQueue(build_dir + "/doneq")
doneq.close()
del doneq
print "doneq inited"
print "init done"
| en | 0.207077 | #!/usr/bin/python #discard_all() | 2.165681 | 2 |
examples/ex_discrete_aeo.py | deanrp2/neorl | 0 | 6617078 | from neorl import DE, GWO, SSA, WOA, AEO, MFO, JAYA, HHO, PSO, ES
import math, random
import sys
#################################
# Define Vessel Function
#Mixed discrete/continuous/grid
#################################
def Vessel(individual):
"""
Pressure vesssel design
x1: thickness (d1) --> discrete value multiple of 0.0625 in
x2: thickness of the heads (d2) ---> categorical value from a pre-defined grid
x3: inner radius (r) ---> cont. value between [10, 200]
x4: length (L) ---> cont. value between [10, 200]
"""
x=individual.copy()
x[0] *= 0.0625 #convert d1 to "in"
y = 0.6224*x[0]*x[2]*x[3]+1.7781*x[1]*x[2]**2+3.1661*x[0]**2*x[3]+19.84*x[0]**2*x[2];
g1 = -x[0]+0.0193*x[2];
g2 = -x[1]+0.00954*x[2];
g3 = -math.pi*x[2]**2*x[3]-(4/3)*math.pi*x[2]**3 + 1296000;
g4 = x[3]-240;
g=[g1,g2,g3,g4]
phi=sum(max(item,0) for item in g)
eps=1e-5 #tolerance to escape the constraint region
penality=1e7 #large penality to add if constraints are violated
if phi > eps:
fitness=phi+penality
else:
fitness=y
return fitness
def init_sample(bounds):
#generate an individual from a bounds dictionary
indv=[]
for key in bounds:
if bounds[key][0] == 'int':
indv.append(random.randint(bounds[key][1], bounds[key][2]))
elif bounds[key][0] == 'float':
indv.append(random.uniform(bounds[key][1], bounds[key][2]))
elif bounds[key][0] == 'grid':
indv.append(random.sample(bounds[key][1],1)[0])
else:
raise Exception ('unknown data type is given, either int, float, or grid are allowed for parameter bounds')
return indv
ngen=5
for item in ['mixed', 'grid', 'float/int', 'float/grid', 'int/grid', 'float', 'int']:
bounds = {}
btype=item #float, int, grid, float/int, float/grid, int/grid, mixed.
print(item, 'is running -----')
if btype=='mixed':
bounds['x1'] = ['int', 1, 99]
bounds['x2'] = ['grid', (0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625)]
bounds['x3'] = ['float', 10, 200]
bounds['x4'] = ['float', 10, 200]
bounds['x5'] = ['grid', ('Hi', 'Bye', 'New')]
bounds['x6'] = ['int', -5, 5]
elif btype=='int/grid':
bounds['x1'] = ['int', 1, 20]
bounds['x2'] = ['grid', (0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625)]
bounds['x3'] = ['int', 10, 200]
bounds['x4'] = ['int', 10, 200]
bounds['x5'] = ['grid', ('Hi', 'Bye', 'New')]
bounds['x6'] = ['int', -5, 5]
elif btype=='float/grid':
bounds['x1'] = ['float', 1, 20]
bounds['x2'] = ['grid', (0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625)]
bounds['x3'] = ['float', 10, 200]
bounds['x4'] = ['float', 10, 200]
bounds['x5'] = ['grid', ('Hi', 'Bye', 'New')]
bounds['x6'] = ['float', -5, 5]
elif btype=='float/int':
bounds['x1'] = ['int', 1, 20]
bounds['x2'] = ['float', 1, 20]
bounds['x3'] = ['int', 10, 200]
bounds['x4'] = ['float', 10, 200]
bounds['x5'] = ['float', -5, 5]
bounds['x6'] = ['int', -5, 5]
elif btype=='float':
bounds['x1'] = ['float', 1, 20]
bounds['x2'] = ['float', 1, 20]
bounds['x3'] = ['float', 10, 200]
bounds['x4'] = ['float', 10, 200]
bounds['x5'] = ['float', -5, 5]
bounds['x6'] = ['float', -5, 5]
elif btype=='int':
bounds['x1'] = ['int', 1, 20]
bounds['x2'] = ['int', 1, 20]
bounds['x3'] = ['int', 10, 200]
bounds['x4'] = ['int', 10, 200]
bounds['x5'] = ['int', -5, 5]
bounds['x6'] = ['int', -5, 5]
elif btype=='grid':
bounds['x1'] = ['grid', (0.0625, 0.125, 0.375, 0.4375, 0.5625, 0.625)]
bounds['x2'] = ['grid', (0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625)]
bounds['x3'] = ['grid', (1,2,3,4,5)]
bounds['x4'] = ['grid', (32,64,128)]
bounds['x5'] = ['grid', ('Hi', 'Bye', 'New')]
bounds['x6'] = ['grid', ('Cat', 'Dog', 'Bird', 'Fish')]
npop=10
x0=[]
for i in range(npop):
x0.append(init_sample(bounds))
########################
# Setup and evolute GWO
########################
gwo=GWO(mode='min', fit=Vessel, bounds=bounds, nwolves=npop, ncores=1, seed=1)
x_gwo, y_gwo, gwo_hist=gwo.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_gwo) == y_gwo
print('GWO=', x_gwo, y_gwo)
########################
# Setup and evolute WOA
########################
woa=WOA(mode='min', bounds=bounds, fit=Vessel, nwhales=npop, a0=1.5, b=1, ncores=1, seed=1)
x_woa, y_woa, woa_hist=woa.evolute(ngen=ngen, x0=x0, verbose=0)
#print(woa_hist['last_pop'])
assert Vessel(x_woa) == y_woa
########################
# Setup and evolute SSA
########################
#setup and evolute SSA
ssa=SSA(mode='min', bounds=bounds, fit=Vessel, nsalps=npop, int_transform='sigmoid', ncores=1, seed=1)
x_ssa, y_ssa, ssa_hist=ssa.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_ssa) == y_ssa
########################
# Setup and evolute DE
########################
de=DE(mode='min', bounds=bounds, fit=Vessel, npop=npop, F=0.5, CR=0.7, int_transform='sigmoid', ncores=1, seed=1)
x_de, y_de, de_hist=de.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_de) == y_de
########################
# Setup and evolute MFO
########################
mfo=MFO(mode='min', bounds=bounds, fit=Vessel, nmoths=npop, int_transform='minmax', ncores=1, seed=1)
x_mfo, y_mfo, mfo_hist=mfo.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_mfo) == y_mfo
########################
# Setup and evolute JAYA
########################
jaya=JAYA(mode='min', bounds=bounds, fit=Vessel, npop=npop, int_transform='sigmoid', ncores=1, seed=1)
x_jaya, y_jaya, jaya_hist=jaya.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_jaya) == y_jaya
########################
# Setup and evolute HHO
########################
hho = HHO(mode='min', bounds=bounds, fit=Vessel, nhawks=npop,
int_transform='minmax', ncores=1, seed=1)
x_hho, y_hho, hho_hist=hho.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_hho) == y_hho
########################
# Setup and evolute PSO
########################
pso=PSO(mode='min', bounds=bounds, fit=Vessel, c1=2.05, c2=2.1, npar=npop,
speed_mech='constric', ncores=1, seed=1)
x_pso, y_pso, pso_hist=pso.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_pso) == y_pso
########################
# Setup and evolute ES
########################
es = ES(mode='min', fit=Vessel, cxmode='cx2point', bounds=bounds,
lambda_=npop, mu=5, cxpb=0.7, mutpb=0.2, seed=1)
x_es, y_es, es_hist=es.evolute(ngen=ngen, x0=x0, verbose=0)
print('ES=', x_es, y_es)
assert Vessel(x_es) == y_es
########################
# Setup and evolute AEO
########################
aeo = AEO(mode='min', bounds=bounds, optimizers=[de, gwo, woa, jaya, hho, pso, es, ssa, mfo], gen_per_cycle=3, fit = Vessel)
x_aeo, y_aeo, aeo_hist = aeo.evolute(30, verbose = 1)
print('AEO=', x_aeo, y_aeo) #not consistent wit other methods
print()
print('--- Something wrong here, the grid variable is not in the original space')
print(aeo.pops[0].members)
assert Vessel(x_aeo) == y_aeo
sys.exit() #remove to complete the full test | from neorl import DE, GWO, SSA, WOA, AEO, MFO, JAYA, HHO, PSO, ES
import math, random
import sys
#################################
# Define Vessel Function
#Mixed discrete/continuous/grid
#################################
def Vessel(individual):
"""
Pressure vesssel design
x1: thickness (d1) --> discrete value multiple of 0.0625 in
x2: thickness of the heads (d2) ---> categorical value from a pre-defined grid
x3: inner radius (r) ---> cont. value between [10, 200]
x4: length (L) ---> cont. value between [10, 200]
"""
x=individual.copy()
x[0] *= 0.0625 #convert d1 to "in"
y = 0.6224*x[0]*x[2]*x[3]+1.7781*x[1]*x[2]**2+3.1661*x[0]**2*x[3]+19.84*x[0]**2*x[2];
g1 = -x[0]+0.0193*x[2];
g2 = -x[1]+0.00954*x[2];
g3 = -math.pi*x[2]**2*x[3]-(4/3)*math.pi*x[2]**3 + 1296000;
g4 = x[3]-240;
g=[g1,g2,g3,g4]
phi=sum(max(item,0) for item in g)
eps=1e-5 #tolerance to escape the constraint region
penality=1e7 #large penality to add if constraints are violated
if phi > eps:
fitness=phi+penality
else:
fitness=y
return fitness
def init_sample(bounds):
#generate an individual from a bounds dictionary
indv=[]
for key in bounds:
if bounds[key][0] == 'int':
indv.append(random.randint(bounds[key][1], bounds[key][2]))
elif bounds[key][0] == 'float':
indv.append(random.uniform(bounds[key][1], bounds[key][2]))
elif bounds[key][0] == 'grid':
indv.append(random.sample(bounds[key][1],1)[0])
else:
raise Exception ('unknown data type is given, either int, float, or grid are allowed for parameter bounds')
return indv
ngen=5
for item in ['mixed', 'grid', 'float/int', 'float/grid', 'int/grid', 'float', 'int']:
bounds = {}
btype=item #float, int, grid, float/int, float/grid, int/grid, mixed.
print(item, 'is running -----')
if btype=='mixed':
bounds['x1'] = ['int', 1, 99]
bounds['x2'] = ['grid', (0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625)]
bounds['x3'] = ['float', 10, 200]
bounds['x4'] = ['float', 10, 200]
bounds['x5'] = ['grid', ('Hi', 'Bye', 'New')]
bounds['x6'] = ['int', -5, 5]
elif btype=='int/grid':
bounds['x1'] = ['int', 1, 20]
bounds['x2'] = ['grid', (0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625)]
bounds['x3'] = ['int', 10, 200]
bounds['x4'] = ['int', 10, 200]
bounds['x5'] = ['grid', ('Hi', 'Bye', 'New')]
bounds['x6'] = ['int', -5, 5]
elif btype=='float/grid':
bounds['x1'] = ['float', 1, 20]
bounds['x2'] = ['grid', (0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625)]
bounds['x3'] = ['float', 10, 200]
bounds['x4'] = ['float', 10, 200]
bounds['x5'] = ['grid', ('Hi', 'Bye', 'New')]
bounds['x6'] = ['float', -5, 5]
elif btype=='float/int':
bounds['x1'] = ['int', 1, 20]
bounds['x2'] = ['float', 1, 20]
bounds['x3'] = ['int', 10, 200]
bounds['x4'] = ['float', 10, 200]
bounds['x5'] = ['float', -5, 5]
bounds['x6'] = ['int', -5, 5]
elif btype=='float':
bounds['x1'] = ['float', 1, 20]
bounds['x2'] = ['float', 1, 20]
bounds['x3'] = ['float', 10, 200]
bounds['x4'] = ['float', 10, 200]
bounds['x5'] = ['float', -5, 5]
bounds['x6'] = ['float', -5, 5]
elif btype=='int':
bounds['x1'] = ['int', 1, 20]
bounds['x2'] = ['int', 1, 20]
bounds['x3'] = ['int', 10, 200]
bounds['x4'] = ['int', 10, 200]
bounds['x5'] = ['int', -5, 5]
bounds['x6'] = ['int', -5, 5]
elif btype=='grid':
bounds['x1'] = ['grid', (0.0625, 0.125, 0.375, 0.4375, 0.5625, 0.625)]
bounds['x2'] = ['grid', (0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625)]
bounds['x3'] = ['grid', (1,2,3,4,5)]
bounds['x4'] = ['grid', (32,64,128)]
bounds['x5'] = ['grid', ('Hi', 'Bye', 'New')]
bounds['x6'] = ['grid', ('Cat', 'Dog', 'Bird', 'Fish')]
npop=10
x0=[]
for i in range(npop):
x0.append(init_sample(bounds))
########################
# Setup and evolute GWO
########################
gwo=GWO(mode='min', fit=Vessel, bounds=bounds, nwolves=npop, ncores=1, seed=1)
x_gwo, y_gwo, gwo_hist=gwo.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_gwo) == y_gwo
print('GWO=', x_gwo, y_gwo)
########################
# Setup and evolute WOA
########################
woa=WOA(mode='min', bounds=bounds, fit=Vessel, nwhales=npop, a0=1.5, b=1, ncores=1, seed=1)
x_woa, y_woa, woa_hist=woa.evolute(ngen=ngen, x0=x0, verbose=0)
#print(woa_hist['last_pop'])
assert Vessel(x_woa) == y_woa
########################
# Setup and evolute SSA
########################
#setup and evolute SSA
ssa=SSA(mode='min', bounds=bounds, fit=Vessel, nsalps=npop, int_transform='sigmoid', ncores=1, seed=1)
x_ssa, y_ssa, ssa_hist=ssa.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_ssa) == y_ssa
########################
# Setup and evolute DE
########################
de=DE(mode='min', bounds=bounds, fit=Vessel, npop=npop, F=0.5, CR=0.7, int_transform='sigmoid', ncores=1, seed=1)
x_de, y_de, de_hist=de.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_de) == y_de
########################
# Setup and evolute MFO
########################
mfo=MFO(mode='min', bounds=bounds, fit=Vessel, nmoths=npop, int_transform='minmax', ncores=1, seed=1)
x_mfo, y_mfo, mfo_hist=mfo.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_mfo) == y_mfo
########################
# Setup and evolute JAYA
########################
jaya=JAYA(mode='min', bounds=bounds, fit=Vessel, npop=npop, int_transform='sigmoid', ncores=1, seed=1)
x_jaya, y_jaya, jaya_hist=jaya.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_jaya) == y_jaya
########################
# Setup and evolute HHO
########################
hho = HHO(mode='min', bounds=bounds, fit=Vessel, nhawks=npop,
int_transform='minmax', ncores=1, seed=1)
x_hho, y_hho, hho_hist=hho.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_hho) == y_hho
########################
# Setup and evolute PSO
########################
pso=PSO(mode='min', bounds=bounds, fit=Vessel, c1=2.05, c2=2.1, npar=npop,
speed_mech='constric', ncores=1, seed=1)
x_pso, y_pso, pso_hist=pso.evolute(ngen=ngen, x0=x0, verbose=0)
assert Vessel(x_pso) == y_pso
########################
# Setup and evolute ES
########################
es = ES(mode='min', fit=Vessel, cxmode='cx2point', bounds=bounds,
lambda_=npop, mu=5, cxpb=0.7, mutpb=0.2, seed=1)
x_es, y_es, es_hist=es.evolute(ngen=ngen, x0=x0, verbose=0)
print('ES=', x_es, y_es)
assert Vessel(x_es) == y_es
########################
# Setup and evolute AEO
########################
aeo = AEO(mode='min', bounds=bounds, optimizers=[de, gwo, woa, jaya, hho, pso, es, ssa, mfo], gen_per_cycle=3, fit = Vessel)
x_aeo, y_aeo, aeo_hist = aeo.evolute(30, verbose = 1)
print('AEO=', x_aeo, y_aeo) #not consistent wit other methods
print()
print('--- Something wrong here, the grid variable is not in the original space')
print(aeo.pops[0].members)
assert Vessel(x_aeo) == y_aeo
sys.exit() #remove to complete the full test | de | 0.376859 | ################################# # Define Vessel Function #Mixed discrete/continuous/grid ################################# Pressure vesssel design
x1: thickness (d1) --> discrete value multiple of 0.0625 in
x2: thickness of the heads (d2) ---> categorical value from a pre-defined grid
x3: inner radius (r) ---> cont. value between [10, 200]
x4: length (L) ---> cont. value between [10, 200] #convert d1 to "in" #tolerance to escape the constraint region #large penality to add if constraints are violated #generate an individual from a bounds dictionary #float, int, grid, float/int, float/grid, int/grid, mixed. ######################## # Setup and evolute GWO ######################## ######################## # Setup and evolute WOA ######################## #print(woa_hist['last_pop']) ######################## # Setup and evolute SSA ######################## #setup and evolute SSA ######################## # Setup and evolute DE ######################## ######################## # Setup and evolute MFO ######################## ######################## # Setup and evolute JAYA ######################## ######################## # Setup and evolute HHO ######################## ######################## # Setup and evolute PSO ######################## ######################## # Setup and evolute ES ######################## ######################## # Setup and evolute AEO ######################## #not consistent wit other methods #remove to complete the full test | 2.697087 | 3 |
mailClient/mailClient.py | gems2tech/network-programming | 0 | 6617079 | <reponame>gems2tech/network-programming
import smtplib
from cryptography.fernet import Fernet
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
with open ('/pathToFilekey/'+'filekey.key','rb') as filekey:
key = filekey.read()
with open('password.txt','rb') as enc_file:
encrypted = enc_file.read()
f = Fernet(key)
decrypted = f.decrypt(encrypted)
password = decrypted.decode("utf-8")
msg = MIMEMultipart()
msg['From'] = 'myName'
msg['To'] = '<EMAIL>' #10 min mail
msg['Subject'] = 'Just A Test'
with open ('message.txt','r') as m:
message = m.read()
msg.attach(MIMEText(message, 'plain'))
filename = 'feld.jpg' # attachment file name
attachment = open(filename, 'rb')
p = MIMEBase('application', 'octet-stream')
p.set_payload(attachment.read())
encoders.encode_base64(p)
p.add_header('Content-Disposition',f'attachment; filename={filename}')
msg.attach(p)
text = msg.as_string()
server = smtplib.SMTP('smtp.live.com', 25)
server.ehlo()
server.starttls()
server.login('<EMAIL>', password)
server.sendmail('<EMAIL>','<EMAIL>',text) #10 min mail
server.quit()
print("Mail sending successful")
| import smtplib
from cryptography.fernet import Fernet
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
with open ('/pathToFilekey/'+'filekey.key','rb') as filekey:
key = filekey.read()
with open('password.txt','rb') as enc_file:
encrypted = enc_file.read()
f = Fernet(key)
decrypted = f.decrypt(encrypted)
password = decrypted.decode("utf-8")
msg = MIMEMultipart()
msg['From'] = 'myName'
msg['To'] = '<EMAIL>' #10 min mail
msg['Subject'] = 'Just A Test'
with open ('message.txt','r') as m:
message = m.read()
msg.attach(MIMEText(message, 'plain'))
filename = 'feld.jpg' # attachment file name
attachment = open(filename, 'rb')
p = MIMEBase('application', 'octet-stream')
p.set_payload(attachment.read())
encoders.encode_base64(p)
p.add_header('Content-Disposition',f'attachment; filename={filename}')
msg.attach(p)
text = msg.as_string()
server = smtplib.SMTP('smtp.live.com', 25)
server.ehlo()
server.starttls()
server.login('<EMAIL>', password)
server.sendmail('<EMAIL>','<EMAIL>',text) #10 min mail
server.quit()
print("Mail sending successful") | en | 0.584497 | #10 min mail # attachment file name #10 min mail | 2.800811 | 3 |
dq/transforms.py | camlsys/degree-quant | 25 | 6617080 | <filename>dq/transforms.py<gh_stars>10-100
"""By convention, masks should have true elements at positions where higher precision should be used"""
import torch
from torch_geometric.data import Batch
from torch_geometric.utils import degree
class ProbabilisticHighDegreeMask:
def __init__(self, low_quantise_prob, high_quantise_prob, per_graph=True):
self.low_prob = low_quantise_prob
self.high_prob = high_quantise_prob
self.per_graph = per_graph
def _process_graph(self, graph):
# Note that:
# 1. The probability of being protected increases as the indegree increases
# 2. All nodes with the same indegree have the same bernoulli p
# 3. you can set this such that all nodes have some probability of being quantised
n = graph.num_nodes
indegree = degree(graph.edge_index[1], n, dtype=torch.long)
counts = torch.bincount(indegree)
step_size = (self.high_prob - self.low_prob) / n
indegree_ps = counts * step_size
indegree_ps = torch.cumsum(indegree_ps, dim=0)
indegree_ps += self.low_prob
graph.prob_mask = indegree_ps[indegree]
return graph
def __call__(self, data):
if self.per_graph and isinstance(data, Batch):
graphs = data.to_data_list()
processed = []
for g in graphs:
g = self._process_graph(g)
processed.append(g)
return Batch.from_data_list(processed)
else:
return self._process_graph(data)
| <filename>dq/transforms.py<gh_stars>10-100
"""By convention, masks should have true elements at positions where higher precision should be used"""
import torch
from torch_geometric.data import Batch
from torch_geometric.utils import degree
class ProbabilisticHighDegreeMask:
def __init__(self, low_quantise_prob, high_quantise_prob, per_graph=True):
self.low_prob = low_quantise_prob
self.high_prob = high_quantise_prob
self.per_graph = per_graph
def _process_graph(self, graph):
# Note that:
# 1. The probability of being protected increases as the indegree increases
# 2. All nodes with the same indegree have the same bernoulli p
# 3. you can set this such that all nodes have some probability of being quantised
n = graph.num_nodes
indegree = degree(graph.edge_index[1], n, dtype=torch.long)
counts = torch.bincount(indegree)
step_size = (self.high_prob - self.low_prob) / n
indegree_ps = counts * step_size
indegree_ps = torch.cumsum(indegree_ps, dim=0)
indegree_ps += self.low_prob
graph.prob_mask = indegree_ps[indegree]
return graph
def __call__(self, data):
if self.per_graph and isinstance(data, Batch):
graphs = data.to_data_list()
processed = []
for g in graphs:
g = self._process_graph(g)
processed.append(g)
return Batch.from_data_list(processed)
else:
return self._process_graph(data)
| en | 0.929881 | By convention, masks should have true elements at positions where higher precision should be used # Note that: # 1. The probability of being protected increases as the indegree increases # 2. All nodes with the same indegree have the same bernoulli p # 3. you can set this such that all nodes have some probability of being quantised | 2.088259 | 2 |
examples/dataclass/config.py | kuwv/python-argufy | 0 | 6617081 | '''Provide example to update variable.'''
from dataclasses import dataclass
@dataclass
class Settings:
var1: str
var2: str = 'default'
| '''Provide example to update variable.'''
from dataclasses import dataclass
@dataclass
class Settings:
var1: str
var2: str = 'default'
| en | 0.573152 | Provide example to update variable. | 2.267674 | 2 |
groupdocs_parser_cloud/apis/__init__.py | groupdocs-parser-cloud/groupdocs-parser-cloud-python | 1 | 6617082 | <gh_stars>1-10
from __future__ import absolute_import
# flake8: noqa
# import apis
from groupdocs_parser_cloud.apis.file_api import FileApi
from groupdocs_parser_cloud.apis.folder_api import FolderApi
from groupdocs_parser_cloud.apis.info_api import InfoApi
from groupdocs_parser_cloud.apis.parse_api import ParseApi
from groupdocs_parser_cloud.apis.storage_api import StorageApi
from groupdocs_parser_cloud.apis.template_api import TemplateApi
| from __future__ import absolute_import
# flake8: noqa
# import apis
from groupdocs_parser_cloud.apis.file_api import FileApi
from groupdocs_parser_cloud.apis.folder_api import FolderApi
from groupdocs_parser_cloud.apis.info_api import InfoApi
from groupdocs_parser_cloud.apis.parse_api import ParseApi
from groupdocs_parser_cloud.apis.storage_api import StorageApi
from groupdocs_parser_cloud.apis.template_api import TemplateApi | eo | 0.155717 | # flake8: noqa # import apis | 1.091106 | 1 |
fe/free_energy.py | fehomi/timemachine | 0 | 6617083 | <filename>fe/free_energy.py
from jax.config import config; config.update("jax_enable_x64", True)
import jax
import numpy as np
from fe import topology
from timemachine.lib import potentials, custom_ops
from timemachine.lib import LangevinIntegrator
from ff.handlers import openmm_deserializer
def get_romol_conf(mol):
"""Coordinates of mol's 0th conformer, in nanometers"""
conformer = mol.GetConformer(0)
guest_conf = np.array(conformer.GetPositions(), dtype=np.float64)
return guest_conf/10 # from angstroms to nm
class BaseFreeEnergy():
@staticmethod
def _get_integrator(combined_masses):
"""
Get a integrator. The resulting impl must be bound to a python handle
whose lifetime is concurrent with that of the context.
"""
seed = np.random.randint(np.iinfo(np.int32).max)
return LangevinIntegrator(
300.0,
1.5e-3,
1.0,
combined_masses,
seed
)
@staticmethod
def _get_system_params_and_potentials(ff_params, topology):
ff_tuples = [
[topology.parameterize_harmonic_bond, (ff_params[0],)],
[topology.parameterize_harmonic_angle, (ff_params[1],)],
[topology.parameterize_periodic_torsion, (ff_params[2], ff_params[3])],
[topology.parameterize_nonbonded, (ff_params[4], ff_params[5])]
]
final_params = []
final_potentials = []
for fn, params in ff_tuples:
combined_params, combined_potential = fn(*params)
final_potentials.append(combined_potential)
final_params.append(combined_params)
return final_params, final_potentials
# this class is serializable.
class AbsoluteFreeEnergy(BaseFreeEnergy):
def __init__(self, mol, ff):
"""
Compute the absolute free energy of a molecule via 4D decoupling.
Parameters
----------
mol: rdkit mol
Ligand to be decoupled
ff: ff.Forcefield
Ligand forcefield
"""
self.mol = mol
self.ff = ff
self.top = topology.BaseTopology(mol, ff)
def prepare_host_edge(self, ff_params, host_system, host_coords):
"""
Prepares the host-edge system
Parameters
----------
ff_params: tuple of np.array
Exactly equal to bond_params, angle_params, proper_params, improper_params, charge_params, lj_params
host_system: openmm.System
openmm System object to be deserialized
host_coords: np.array
Nx3 array of atomic coordinates
Returns
-------
4 tuple
unbound_potentials, system_params, combined_masses, combined_coords
"""
ligand_masses = [a.GetMass() for a in self.mol.GetAtoms()]
ligand_coords = get_romol_conf(self.mol)
host_bps, host_masses = openmm_deserializer.deserialize_system(host_system, cutoff=1.2)
num_host_atoms = host_coords.shape[0]
hgt = topology.HostGuestTopology(host_bps, self.top)
final_params, final_potentials = self._get_system_params_and_potentials(ff_params, hgt)
combined_masses = np.concatenate([host_masses, ligand_masses])
combined_coords = np.concatenate([host_coords, ligand_coords])
return final_potentials, final_params, combined_masses, combined_coords
# this class is serializable.
class RelativeFreeEnergy(BaseFreeEnergy):
def __init__(self, single_topology: topology.SingleTopology, label=None):
self.top = single_topology
self.label = label
@property
def mol_a(self):
return self.top.mol_a
@property
def mol_b(self):
return self.top.mol_b
@property
def core(self):
return self.top.core
@property
def ff(self):
return self.top.ff
def _get_integrator(self, combined_masses):
"""
Get a integrator. The resulting impl must be bound to a python handle
whose lifetime is concurrent with that of the context.
"""
seed = np.random.randint(np.iinfo(np.int32).max)
return LangevinIntegrator(
300.0,
1.5e-3,
1.0,
combined_masses,
seed
)
def prepare_vacuum_edge(self, ff_params):
"""
Prepares the vacuum system.
Parameters
----------
ff_params: tuple of np.array
Exactly equal to bond_params, angle_params, proper_params, improper_params, charge_params, lj_params
Returns
-------
4 tuple
unbound_potentials, system_parameters, combined_masses, combined_coords
"""
ligand_masses_a = [a.GetMass() for a in self.mol_a.GetAtoms()]
ligand_masses_b = [b.GetMass() for b in self.mol_b.GetAtoms()]
ligand_coords_a = get_romol_conf(self.mol_a)
ligand_coords_b = get_romol_conf(self.mol_b)
final_params, final_potentials = self._get_system_params_and_potentials(ff_params, self.top)
combined_masses = np.mean(self.top.interpolate_params(ligand_masses_a, ligand_masses_b), axis=0)
combined_coords = np.mean(self.top.interpolate_params(ligand_coords_a, ligand_coords_b), axis=0)
return final_potentials, final_params, combined_masses, combined_coords
def prepare_host_edge(self, ff_params, host_system, host_coords):
"""
Prepares the host-edge system
Parameters
----------
ff_params: tuple of np.array
Exactly equal to bond_params, angle_params, proper_params, improper_params, charge_params, lj_params
host_system: openmm.System
openmm System object to be deserialized
host_coords: np.array
Nx3 array of atomic coordinates
Returns
-------
4 tuple
unbound_potentials, system_params, combined_masses, combined_coords
"""
ligand_masses_a = [a.GetMass() for a in self.mol_a.GetAtoms()]
ligand_masses_b = [b.GetMass() for b in self.mol_b.GetAtoms()]
# extract the 0th conformer
ligand_coords_a = get_romol_conf(self.mol_a)
ligand_coords_b = get_romol_conf(self.mol_b)
host_bps, host_masses = openmm_deserializer.deserialize_system(host_system, cutoff=1.2)
num_host_atoms = host_coords.shape[0]
hgt = topology.HostGuestTopology(host_bps, self.top)
final_params, final_potentials = self._get_system_params_and_potentials(ff_params, hgt)
combined_masses = np.concatenate([host_masses, np.mean(self.top.interpolate_params(ligand_masses_a, ligand_masses_b), axis=0)])
combined_coords = np.concatenate([host_coords, np.mean(self.top.interpolate_params(ligand_coords_a, ligand_coords_b), axis=0)])
return final_potentials, final_params, combined_masses, combined_coords
def construct_lambda_schedule(num_windows):
"""Generate a length-num_windows list of lambda values from 0.0 up to 1.0
Notes
-----
manually optimized by YTZ
"""
A = int(.35 * num_windows)
B = int(.30 * num_windows)
C = num_windows - A - B
# Empirically, we see the largest variance in std <du/dl> near the endpoints in the nonbonded
# terms. Bonded terms are roughly linear. So we add more lambda windows at the endpoint to
# help improve convergence.
lambda_schedule = np.concatenate([
np.linspace(0.0, 0.25, A, endpoint=False),
np.linspace(0.25, 0.75, B, endpoint=False),
np.linspace(0.75, 1.0, C, endpoint=True)
])
assert len(lambda_schedule) == num_windows
return lambda_schedule
| <filename>fe/free_energy.py
from jax.config import config; config.update("jax_enable_x64", True)
import jax
import numpy as np
from fe import topology
from timemachine.lib import potentials, custom_ops
from timemachine.lib import LangevinIntegrator
from ff.handlers import openmm_deserializer
def get_romol_conf(mol):
"""Coordinates of mol's 0th conformer, in nanometers"""
conformer = mol.GetConformer(0)
guest_conf = np.array(conformer.GetPositions(), dtype=np.float64)
return guest_conf/10 # from angstroms to nm
class BaseFreeEnergy():
@staticmethod
def _get_integrator(combined_masses):
"""
Get a integrator. The resulting impl must be bound to a python handle
whose lifetime is concurrent with that of the context.
"""
seed = np.random.randint(np.iinfo(np.int32).max)
return LangevinIntegrator(
300.0,
1.5e-3,
1.0,
combined_masses,
seed
)
@staticmethod
def _get_system_params_and_potentials(ff_params, topology):
ff_tuples = [
[topology.parameterize_harmonic_bond, (ff_params[0],)],
[topology.parameterize_harmonic_angle, (ff_params[1],)],
[topology.parameterize_periodic_torsion, (ff_params[2], ff_params[3])],
[topology.parameterize_nonbonded, (ff_params[4], ff_params[5])]
]
final_params = []
final_potentials = []
for fn, params in ff_tuples:
combined_params, combined_potential = fn(*params)
final_potentials.append(combined_potential)
final_params.append(combined_params)
return final_params, final_potentials
# this class is serializable.
class AbsoluteFreeEnergy(BaseFreeEnergy):
def __init__(self, mol, ff):
"""
Compute the absolute free energy of a molecule via 4D decoupling.
Parameters
----------
mol: rdkit mol
Ligand to be decoupled
ff: ff.Forcefield
Ligand forcefield
"""
self.mol = mol
self.ff = ff
self.top = topology.BaseTopology(mol, ff)
def prepare_host_edge(self, ff_params, host_system, host_coords):
"""
Prepares the host-edge system
Parameters
----------
ff_params: tuple of np.array
Exactly equal to bond_params, angle_params, proper_params, improper_params, charge_params, lj_params
host_system: openmm.System
openmm System object to be deserialized
host_coords: np.array
Nx3 array of atomic coordinates
Returns
-------
4 tuple
unbound_potentials, system_params, combined_masses, combined_coords
"""
ligand_masses = [a.GetMass() for a in self.mol.GetAtoms()]
ligand_coords = get_romol_conf(self.mol)
host_bps, host_masses = openmm_deserializer.deserialize_system(host_system, cutoff=1.2)
num_host_atoms = host_coords.shape[0]
hgt = topology.HostGuestTopology(host_bps, self.top)
final_params, final_potentials = self._get_system_params_and_potentials(ff_params, hgt)
combined_masses = np.concatenate([host_masses, ligand_masses])
combined_coords = np.concatenate([host_coords, ligand_coords])
return final_potentials, final_params, combined_masses, combined_coords
# this class is serializable.
class RelativeFreeEnergy(BaseFreeEnergy):
def __init__(self, single_topology: topology.SingleTopology, label=None):
self.top = single_topology
self.label = label
@property
def mol_a(self):
return self.top.mol_a
@property
def mol_b(self):
return self.top.mol_b
@property
def core(self):
return self.top.core
@property
def ff(self):
return self.top.ff
def _get_integrator(self, combined_masses):
"""
Get a integrator. The resulting impl must be bound to a python handle
whose lifetime is concurrent with that of the context.
"""
seed = np.random.randint(np.iinfo(np.int32).max)
return LangevinIntegrator(
300.0,
1.5e-3,
1.0,
combined_masses,
seed
)
def prepare_vacuum_edge(self, ff_params):
"""
Prepares the vacuum system.
Parameters
----------
ff_params: tuple of np.array
Exactly equal to bond_params, angle_params, proper_params, improper_params, charge_params, lj_params
Returns
-------
4 tuple
unbound_potentials, system_parameters, combined_masses, combined_coords
"""
ligand_masses_a = [a.GetMass() for a in self.mol_a.GetAtoms()]
ligand_masses_b = [b.GetMass() for b in self.mol_b.GetAtoms()]
ligand_coords_a = get_romol_conf(self.mol_a)
ligand_coords_b = get_romol_conf(self.mol_b)
final_params, final_potentials = self._get_system_params_and_potentials(ff_params, self.top)
combined_masses = np.mean(self.top.interpolate_params(ligand_masses_a, ligand_masses_b), axis=0)
combined_coords = np.mean(self.top.interpolate_params(ligand_coords_a, ligand_coords_b), axis=0)
return final_potentials, final_params, combined_masses, combined_coords
def prepare_host_edge(self, ff_params, host_system, host_coords):
"""
Prepares the host-edge system
Parameters
----------
ff_params: tuple of np.array
Exactly equal to bond_params, angle_params, proper_params, improper_params, charge_params, lj_params
host_system: openmm.System
openmm System object to be deserialized
host_coords: np.array
Nx3 array of atomic coordinates
Returns
-------
4 tuple
unbound_potentials, system_params, combined_masses, combined_coords
"""
ligand_masses_a = [a.GetMass() for a in self.mol_a.GetAtoms()]
ligand_masses_b = [b.GetMass() for b in self.mol_b.GetAtoms()]
# extract the 0th conformer
ligand_coords_a = get_romol_conf(self.mol_a)
ligand_coords_b = get_romol_conf(self.mol_b)
host_bps, host_masses = openmm_deserializer.deserialize_system(host_system, cutoff=1.2)
num_host_atoms = host_coords.shape[0]
hgt = topology.HostGuestTopology(host_bps, self.top)
final_params, final_potentials = self._get_system_params_and_potentials(ff_params, hgt)
combined_masses = np.concatenate([host_masses, np.mean(self.top.interpolate_params(ligand_masses_a, ligand_masses_b), axis=0)])
combined_coords = np.concatenate([host_coords, np.mean(self.top.interpolate_params(ligand_coords_a, ligand_coords_b), axis=0)])
return final_potentials, final_params, combined_masses, combined_coords
def construct_lambda_schedule(num_windows):
"""Generate a length-num_windows list of lambda values from 0.0 up to 1.0
Notes
-----
manually optimized by YTZ
"""
A = int(.35 * num_windows)
B = int(.30 * num_windows)
C = num_windows - A - B
# Empirically, we see the largest variance in std <du/dl> near the endpoints in the nonbonded
# terms. Bonded terms are roughly linear. So we add more lambda windows at the endpoint to
# help improve convergence.
lambda_schedule = np.concatenate([
np.linspace(0.0, 0.25, A, endpoint=False),
np.linspace(0.25, 0.75, B, endpoint=False),
np.linspace(0.75, 1.0, C, endpoint=True)
])
assert len(lambda_schedule) == num_windows
return lambda_schedule
| en | 0.65978 | Coordinates of mol's 0th conformer, in nanometers # from angstroms to nm Get a integrator. The resulting impl must be bound to a python handle whose lifetime is concurrent with that of the context. # this class is serializable. Compute the absolute free energy of a molecule via 4D decoupling. Parameters ---------- mol: rdkit mol Ligand to be decoupled ff: ff.Forcefield Ligand forcefield Prepares the host-edge system Parameters ---------- ff_params: tuple of np.array Exactly equal to bond_params, angle_params, proper_params, improper_params, charge_params, lj_params host_system: openmm.System openmm System object to be deserialized host_coords: np.array Nx3 array of atomic coordinates Returns ------- 4 tuple unbound_potentials, system_params, combined_masses, combined_coords # this class is serializable. Get a integrator. The resulting impl must be bound to a python handle whose lifetime is concurrent with that of the context. Prepares the vacuum system. Parameters ---------- ff_params: tuple of np.array Exactly equal to bond_params, angle_params, proper_params, improper_params, charge_params, lj_params Returns ------- 4 tuple unbound_potentials, system_parameters, combined_masses, combined_coords Prepares the host-edge system Parameters ---------- ff_params: tuple of np.array Exactly equal to bond_params, angle_params, proper_params, improper_params, charge_params, lj_params host_system: openmm.System openmm System object to be deserialized host_coords: np.array Nx3 array of atomic coordinates Returns ------- 4 tuple unbound_potentials, system_params, combined_masses, combined_coords # extract the 0th conformer Generate a length-num_windows list of lambda values from 0.0 up to 1.0 Notes ----- manually optimized by YTZ # Empirically, we see the largest variance in std <du/dl> near the endpoints in the nonbonded # terms. Bonded terms are roughly linear. So we add more lambda windows at the endpoint to # help improve convergence. | 1.883615 | 2 |
testfunctions.py | ijstokes/functions | 0 | 6617084 | <reponame>ijstokes/functions
__author__ = 'ijstokes'
# 1. Import the module we want to test
import functions
# 2. Import unittest
import unittest
# 3. Create a class that subclasses TestCase to encapsulate a set of tests
class TestFunctions(unittest.TestCase):
# 4. Create methods whose names are prefixed with "test_"
def test_adder(self):
# 5. Exercise the function under test
result = functions.adder(2,3)
# 6. Assert some expected condition or result
self.assertEqual(result, 5)
def test_lambda(self):
result = functions.adder_lambda(10, 20)
self.assertEqual(result, 30)
def test_class(self):
" a test case for the Class-based function "
pass
def test_partial(self):
result = functions.add10(7)
self.assertEqual(result, 17)
# 7. (optional) for convenience, make the testing module "runnable", to run
# all the tests in this module.
if __name__ == '__main__':
unittest.main() | __author__ = 'ijstokes'
# 1. Import the module we want to test
import functions
# 2. Import unittest
import unittest
# 3. Create a class that subclasses TestCase to encapsulate a set of tests
class TestFunctions(unittest.TestCase):
# 4. Create methods whose names are prefixed with "test_"
def test_adder(self):
# 5. Exercise the function under test
result = functions.adder(2,3)
# 6. Assert some expected condition or result
self.assertEqual(result, 5)
def test_lambda(self):
result = functions.adder_lambda(10, 20)
self.assertEqual(result, 30)
def test_class(self):
" a test case for the Class-based function "
pass
def test_partial(self):
result = functions.add10(7)
self.assertEqual(result, 17)
# 7. (optional) for convenience, make the testing module "runnable", to run
# all the tests in this module.
if __name__ == '__main__':
unittest.main() | en | 0.694482 | # 1. Import the module we want to test # 2. Import unittest # 3. Create a class that subclasses TestCase to encapsulate a set of tests # 4. Create methods whose names are prefixed with "test_" # 5. Exercise the function under test # 6. Assert some expected condition or result # 7. (optional) for convenience, make the testing module "runnable", to run # all the tests in this module. | 3.481103 | 3 |
tests/test_client.py | RenaissanceAI/ExtractTable-py | 0 | 6617085 | <filename>tests/test_client.py<gh_stars>0
import io
import pytest
from ExtractTable.client import ExtractTable
from ExtractTable.common import UsageStats
from ExtractTable.exceptions import ServiceError
from tests.constants import API_KEY, FILE_PATH, RESULTS_FOLDER
@pytest.fixture
def client():
return ExtractTable(API_KEY)
def test_process_file(client: ExtractTable):
assert not (client.process_file(FILE_PATH, RESULTS_FOLDER))
def test_process_file_index(client: ExtractTable):
assert not (client.process_file(FILE_PATH, RESULTS_FOLDER, True))
def test_check_usage(client: ExtractTable):
assert isinstance(client.check_usage(), UsageStats)
def test_trigger_process_fail(client: ExtractTable):
with pytest.raises(ServiceError):
client.trigger_process(io.BytesIO())
def test_get_result_fail(client: ExtractTable):
with pytest.raises(ServiceError):
assert client.get_result('')
| <filename>tests/test_client.py<gh_stars>0
import io
import pytest
from ExtractTable.client import ExtractTable
from ExtractTable.common import UsageStats
from ExtractTable.exceptions import ServiceError
from tests.constants import API_KEY, FILE_PATH, RESULTS_FOLDER
@pytest.fixture
def client():
return ExtractTable(API_KEY)
def test_process_file(client: ExtractTable):
assert not (client.process_file(FILE_PATH, RESULTS_FOLDER))
def test_process_file_index(client: ExtractTable):
assert not (client.process_file(FILE_PATH, RESULTS_FOLDER, True))
def test_check_usage(client: ExtractTable):
assert isinstance(client.check_usage(), UsageStats)
def test_trigger_process_fail(client: ExtractTable):
with pytest.raises(ServiceError):
client.trigger_process(io.BytesIO())
def test_get_result_fail(client: ExtractTable):
with pytest.raises(ServiceError):
assert client.get_result('')
| none | 1 | 1.9827 | 2 | |
extract_pulses.py | dneise/crosscheck_data_from_taka | 0 | 6617086 | """
Usage:
extract_pulses.py [options]
Options:
--input PATH path to file containing test pulses [default: LnG40.dat]
--offset PATH path to textfile with offset ala Taka [default: Ped300Hz.dat]
--tc PATH path to csv containting cell_widths [default: local_tc.csv]
--channel N channel number to be analyszed [default: 0]
--gain NAME name of gain_type to be analysed. high/low [default: high]
--maxevents N number of events to be used [default: 20000]
--int_window N size of integration window [default: 7]
"""
import dragonboard as dr
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm as progress_bar
import time
import pandas as pd
from docopt import docopt
from scipy.interpolate import interp1d
from matplotlib.colors import LogNorm
import hist2d
from functools import partial
import scipy
def digital_leading_edge_discriminator(data, time, threshold=0, window_length=0):
z = np.where(np.diff(np.signbit(data-threshold)))[0][0]
if window_length == 0:
# There is no data to fit, so we simply do it by and ... saving time.
time_before = time[z]
time_after = time[z+1]
value_before = data[z]
value_after = data[z+1]
slope = (value_after - value_before)/(time_after - time_before)
# value = value_before + delta_time * slope
# threshold = value_before + delta_time_0 * slope
delta_time_0 = (threshold - value_before) / slope
return time_before + delta_time_0
else:
s = slice(z-window_length, z+2+window_length)
m, b = np.polyfit(time[s], data[s], deg=1)
return (threshold-b)/m
args = docopt(__doc__)
args["--channel"] = int(args["--channel"])
args["--int_window"] = int(args["--int_window"])
assert args["--gain"] in ["high", "low"]
try:
args["--maxevents"] = int(args["--maxevents"])
except ValueError:
args["--maxevents"] = None
print(args)
cell_width = pd.read_csv(args["--tc"])["cell_width_mean"].values
template_orig = pd.read_csv("pulse_dataframe.csv")
template = template_orig["pulse_mode"].values[60:180]
template /= template.max()
tc_base_name = args["--tc"][:-4]
offset = np.genfromtxt(args["--offset"])[:,0]
# trick to omit np.roll
offset = np.concatenate((offset, offset))
cell_width = np.concatenate([cell_width]*5)
# for midpoint_rule each sample v_i gets mutiplied with 1/2 * (d_{i-1} + d_i)
midpoint_width = 1/2 * (cell_width + np.roll(cell_width, -1))
half_integration_window = (args["--int_window"] - 1) // 2
ch = args["--channel"]
gain = args["--gain"]
run = dr.EventGenerator(args["--input"], max_events=args["--maxevents"])
NN = min(len(run), args["--maxevents"])
integral = np.zeros(NN, dtype='f4')
integral_weighted = np.zeros(NN, dtype='f4')
max_pos = np.zeros(NN, dtype='i4')
arrival_time = np.zeros(NN, dtype='f4')
arrival_time_no_calib = np.zeros(NN, dtype='f4')
trapz = np.zeros(NN, dtype='f4')
simps = np.zeros(NN, dtype='f4')
for i, event in enumerate(progress_bar(run, leave=True)):
raw_data = event.data[ch][gain]
stop_cell = event.header.stop_cells[ch][gain]
calibrated = raw_data - offset[stop_cell:stop_cell+run.roi]
t = cell_width[stop_cell:stop_cell+run.roi].cumsum()
max_pos[i] = np.argmax(calibrated)
s = slice(max_pos[i]-half_integration_window, max_pos[i]+half_integration_window+1)
samples = np.arange(s.start, s.stop)
cells = dr.sample2cell(samples, stop_cell, total_cells=1024)
DLE = partial(digital_leading_edge_discriminator, data=calibrated, threshold=1000)
arrival_time[i] = DLE(time=t)
arrival_time_no_calib[i] = DLE(time=np.arange(len(calibrated)))
integral[i] = calibrated[s].sum()
integral_weighted[i] = (calibrated[s] * midpoint_width[cells]).sum()
trapz[i] = np.trapz(calibrated[s], t[s])
simps[i] = scipy.integrate.simps(calibrated[s], t[s])
df = pd.DataFrame({
"integral": integral,
"integral_weighted": integral_weighted,
"max_pos": max_pos,
"arrival_time": arrival_time,
"arrival_time_no_calib": arrival_time_no_calib,
"trapz": trapz,
"simps": simps,
})
plt.figure()
names=["integral", "integral_weighted", "trapz", "simps"]
for name in names:
rel_width_in_percent = df[name].std()/df[name].mean() * 100
plt.hist(df[name], bins=np.arange(3500, 6500, 20), histtype="step", log=False, label="{0}:$\sigma$={1:.1f}%".format(name, rel_width_in_percent))
plt.grid()
plt.legend(loc="best")
plt.xlabel("charge [a.u.]")
plt.title("Charge Resolution with {}".format(tc_base_name))
plt.savefig("charge_resolution_{}.png".format(tc_base_name))
plt.figure()
names = ["max_pos", "arrival_time", "arrival_time_no_calib"]
for name in names:
width_in_ns = df[name].std()
plt.hist(df[name], bins=np.linspace(50, 65, 76), histtype="step", log=False, label="{0}:$\sigma$={1:.3f}ns".format(name, width_in_ns))
plt.grid()
plt.legend(loc="best")
plt.xlabel("time [ns]")
plt.title("Time Resolution with {}".format(tc_base_name))
plt.savefig("time_resolution_{}.png".format(tc_base_name)) | """
Usage:
extract_pulses.py [options]
Options:
--input PATH path to file containing test pulses [default: LnG40.dat]
--offset PATH path to textfile with offset ala Taka [default: Ped300Hz.dat]
--tc PATH path to csv containting cell_widths [default: local_tc.csv]
--channel N channel number to be analyszed [default: 0]
--gain NAME name of gain_type to be analysed. high/low [default: high]
--maxevents N number of events to be used [default: 20000]
--int_window N size of integration window [default: 7]
"""
import dragonboard as dr
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm as progress_bar
import time
import pandas as pd
from docopt import docopt
from scipy.interpolate import interp1d
from matplotlib.colors import LogNorm
import hist2d
from functools import partial
import scipy
def digital_leading_edge_discriminator(data, time, threshold=0, window_length=0):
z = np.where(np.diff(np.signbit(data-threshold)))[0][0]
if window_length == 0:
# There is no data to fit, so we simply do it by and ... saving time.
time_before = time[z]
time_after = time[z+1]
value_before = data[z]
value_after = data[z+1]
slope = (value_after - value_before)/(time_after - time_before)
# value = value_before + delta_time * slope
# threshold = value_before + delta_time_0 * slope
delta_time_0 = (threshold - value_before) / slope
return time_before + delta_time_0
else:
s = slice(z-window_length, z+2+window_length)
m, b = np.polyfit(time[s], data[s], deg=1)
return (threshold-b)/m
args = docopt(__doc__)
args["--channel"] = int(args["--channel"])
args["--int_window"] = int(args["--int_window"])
assert args["--gain"] in ["high", "low"]
try:
args["--maxevents"] = int(args["--maxevents"])
except ValueError:
args["--maxevents"] = None
print(args)
cell_width = pd.read_csv(args["--tc"])["cell_width_mean"].values
template_orig = pd.read_csv("pulse_dataframe.csv")
template = template_orig["pulse_mode"].values[60:180]
template /= template.max()
tc_base_name = args["--tc"][:-4]
offset = np.genfromtxt(args["--offset"])[:,0]
# trick to omit np.roll
offset = np.concatenate((offset, offset))
cell_width = np.concatenate([cell_width]*5)
# for midpoint_rule each sample v_i gets mutiplied with 1/2 * (d_{i-1} + d_i)
midpoint_width = 1/2 * (cell_width + np.roll(cell_width, -1))
half_integration_window = (args["--int_window"] - 1) // 2
ch = args["--channel"]
gain = args["--gain"]
run = dr.EventGenerator(args["--input"], max_events=args["--maxevents"])
NN = min(len(run), args["--maxevents"])
integral = np.zeros(NN, dtype='f4')
integral_weighted = np.zeros(NN, dtype='f4')
max_pos = np.zeros(NN, dtype='i4')
arrival_time = np.zeros(NN, dtype='f4')
arrival_time_no_calib = np.zeros(NN, dtype='f4')
trapz = np.zeros(NN, dtype='f4')
simps = np.zeros(NN, dtype='f4')
for i, event in enumerate(progress_bar(run, leave=True)):
raw_data = event.data[ch][gain]
stop_cell = event.header.stop_cells[ch][gain]
calibrated = raw_data - offset[stop_cell:stop_cell+run.roi]
t = cell_width[stop_cell:stop_cell+run.roi].cumsum()
max_pos[i] = np.argmax(calibrated)
s = slice(max_pos[i]-half_integration_window, max_pos[i]+half_integration_window+1)
samples = np.arange(s.start, s.stop)
cells = dr.sample2cell(samples, stop_cell, total_cells=1024)
DLE = partial(digital_leading_edge_discriminator, data=calibrated, threshold=1000)
arrival_time[i] = DLE(time=t)
arrival_time_no_calib[i] = DLE(time=np.arange(len(calibrated)))
integral[i] = calibrated[s].sum()
integral_weighted[i] = (calibrated[s] * midpoint_width[cells]).sum()
trapz[i] = np.trapz(calibrated[s], t[s])
simps[i] = scipy.integrate.simps(calibrated[s], t[s])
df = pd.DataFrame({
"integral": integral,
"integral_weighted": integral_weighted,
"max_pos": max_pos,
"arrival_time": arrival_time,
"arrival_time_no_calib": arrival_time_no_calib,
"trapz": trapz,
"simps": simps,
})
plt.figure()
names=["integral", "integral_weighted", "trapz", "simps"]
for name in names:
rel_width_in_percent = df[name].std()/df[name].mean() * 100
plt.hist(df[name], bins=np.arange(3500, 6500, 20), histtype="step", log=False, label="{0}:$\sigma$={1:.1f}%".format(name, rel_width_in_percent))
plt.grid()
plt.legend(loc="best")
plt.xlabel("charge [a.u.]")
plt.title("Charge Resolution with {}".format(tc_base_name))
plt.savefig("charge_resolution_{}.png".format(tc_base_name))
plt.figure()
names = ["max_pos", "arrival_time", "arrival_time_no_calib"]
for name in names:
width_in_ns = df[name].std()
plt.hist(df[name], bins=np.linspace(50, 65, 76), histtype="step", log=False, label="{0}:$\sigma$={1:.3f}ns".format(name, width_in_ns))
plt.grid()
plt.legend(loc="best")
plt.xlabel("time [ns]")
plt.title("Time Resolution with {}".format(tc_base_name))
plt.savefig("time_resolution_{}.png".format(tc_base_name)) | en | 0.565823 | Usage: extract_pulses.py [options] Options: --input PATH path to file containing test pulses [default: LnG40.dat] --offset PATH path to textfile with offset ala Taka [default: Ped300Hz.dat] --tc PATH path to csv containting cell_widths [default: local_tc.csv] --channel N channel number to be analyszed [default: 0] --gain NAME name of gain_type to be analysed. high/low [default: high] --maxevents N number of events to be used [default: 20000] --int_window N size of integration window [default: 7] # There is no data to fit, so we simply do it by and ... saving time. # value = value_before + delta_time * slope # threshold = value_before + delta_time_0 * slope # trick to omit np.roll # for midpoint_rule each sample v_i gets mutiplied with 1/2 * (d_{i-1} + d_i) | 2.433843 | 2 |
gallery/02_animated_CDS/02_animated_CDS.py | cclark1e/paraSBOLv | 12 | 6617087 | <reponame>cclark1e/paraSBOLv
#!/usr/bin/env python
"""
Animated CDS with random shape and style
"""
import numpy as np
import parasbolv as psv
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Setup the animation
np.random.seed(1)
renderer = psv.GlyphRenderer()
user_parameters = {}
cds_style = {}
fig, ax = plt.subplots()
def run(data):
# Clear the axis and then draw
ax.clear()
ax.set_aspect('equal')
ax.set_xticks([])
ax.set_yticks([])
ax.axis('off')
ax.set_ylim([25,75])
ax.set_xlim([0,70])
user_parameters['height'] = np.random.uniform(10, 20)
user_parameters['width'] = np.random.uniform(10, 20)
user_parameters['arrowbody_height'] = np.random.uniform(4, 10)
user_parameters['arrowhead_width'] = np.random.uniform(5, 9)
cds_style['cds'] = {'facecolor': (np.random.uniform(0, 1),
np.random.uniform(0, 1),
np.random.uniform(0, 1)),
'edgecolor': (np.random.uniform(0, 1),
np.random.uniform(0, 1),
np.random.uniform(0, 1)),
'linewidth': np.random.uniform(1, 10)}
renderer.draw_glyph(ax, 'CDS', (20, 50), user_parameters=user_parameters, user_style=cds_style)
ani = animation.FuncAnimation(fig, run, None, blit=False, interval=10,
repeat=False, init_func=None)
ani.save('02_animated_CDS.gif', fps=30)
# Let the rave begin!
plt.show() | #!/usr/bin/env python
"""
Animated CDS with random shape and style
"""
import numpy as np
import parasbolv as psv
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Setup the animation
np.random.seed(1)
renderer = psv.GlyphRenderer()
user_parameters = {}
cds_style = {}
fig, ax = plt.subplots()
def run(data):
# Clear the axis and then draw
ax.clear()
ax.set_aspect('equal')
ax.set_xticks([])
ax.set_yticks([])
ax.axis('off')
ax.set_ylim([25,75])
ax.set_xlim([0,70])
user_parameters['height'] = np.random.uniform(10, 20)
user_parameters['width'] = np.random.uniform(10, 20)
user_parameters['arrowbody_height'] = np.random.uniform(4, 10)
user_parameters['arrowhead_width'] = np.random.uniform(5, 9)
cds_style['cds'] = {'facecolor': (np.random.uniform(0, 1),
np.random.uniform(0, 1),
np.random.uniform(0, 1)),
'edgecolor': (np.random.uniform(0, 1),
np.random.uniform(0, 1),
np.random.uniform(0, 1)),
'linewidth': np.random.uniform(1, 10)}
renderer.draw_glyph(ax, 'CDS', (20, 50), user_parameters=user_parameters, user_style=cds_style)
ani = animation.FuncAnimation(fig, run, None, blit=False, interval=10,
repeat=False, init_func=None)
ani.save('02_animated_CDS.gif', fps=30)
# Let the rave begin!
plt.show() | en | 0.784929 | #!/usr/bin/env python Animated CDS with random shape and style # Setup the animation # Clear the axis and then draw # Let the rave begin! | 2.77038 | 3 |
test_crawler_html.py | martin5696/Joogle_Search | 0 | 6617088 | <reponame>martin5696/Joogle_Search
from bottle import get, route, run, template
@get('/')
def default():
return template('test_html_1')
@route('/test')
def first_link():
return template('test_html_2')
run (host='localhost', port=8080, debug=True)
| from bottle import get, route, run, template
@get('/')
def default():
return template('test_html_1')
@route('/test')
def first_link():
return template('test_html_2')
run (host='localhost', port=8080, debug=True) | none | 1 | 1.969987 | 2 | |
oasislmf/utils/status.py | OasisLMF/OasisLMF | 88 | 6617089 | __all__ = [
'OASIS_KEYS_STATUS',
'OASIS_TASK_STATUS',
'OASIS_KEYS_STATUS_MODELLED'
]
OASIS_KEYS_SC = 'success'
OASIS_KEYS_FL = 'fail'
OASIS_KEYS_NM = 'nomatch'
OASIS_KEYS_FA = 'fail_ap'
OASIS_KEYS_FV = 'fail_v'
OASIS_KEYS_NR = 'notatrisk'
OASIS_KEYS_XX = 'noreturn'
OASIS_KEYS_STATUS = {
'success': {'id': OASIS_KEYS_SC, 'desc': 'Success'},
'fail': {'id': OASIS_KEYS_FL, 'desc': 'Failure'},
'nomatch': {'id': OASIS_KEYS_NM, 'desc': 'No match'},
'fail_ap': {'id': OASIS_KEYS_FA, 'desc': 'Failure areaperil'},
'fail_v': {'id': OASIS_KEYS_FV, 'desc': 'Failure vulnerability'},
'notatrisk': {'id': OASIS_KEYS_NR, 'desc': 'Modelled but not at risk'},
'noreturn': {'id': OASIS_KEYS_XX, 'desc': 'No key returned from lookup'}
}
OASIS_UNKNOWN_ID = -1
# list of statuses classed as "modelled"
OASIS_KEYS_STATUS_MODELLED = [OASIS_KEYS_SC,OASIS_KEYS_NR]
OASIS_TASK_PN = 'PENDING'
OASIS_TASK_RN = 'RUNNING'
OASIS_TASK_SC = 'SUCCESS'
OASIS_TASK_FL = 'FAILURE'
OASIS_TASK_STATUS = {
'pending': {'id': OASIS_TASK_PN, 'desc': 'Pending'},
'running': {'id': OASIS_TASK_RN, 'desc': 'Running'},
'success': {'id': OASIS_TASK_SC, 'desc': 'Success'},
'failure': {'id': OASIS_TASK_FL, 'desc': 'Failure'}
}
| __all__ = [
'OASIS_KEYS_STATUS',
'OASIS_TASK_STATUS',
'OASIS_KEYS_STATUS_MODELLED'
]
OASIS_KEYS_SC = 'success'
OASIS_KEYS_FL = 'fail'
OASIS_KEYS_NM = 'nomatch'
OASIS_KEYS_FA = 'fail_ap'
OASIS_KEYS_FV = 'fail_v'
OASIS_KEYS_NR = 'notatrisk'
OASIS_KEYS_XX = 'noreturn'
OASIS_KEYS_STATUS = {
'success': {'id': OASIS_KEYS_SC, 'desc': 'Success'},
'fail': {'id': OASIS_KEYS_FL, 'desc': 'Failure'},
'nomatch': {'id': OASIS_KEYS_NM, 'desc': 'No match'},
'fail_ap': {'id': OASIS_KEYS_FA, 'desc': 'Failure areaperil'},
'fail_v': {'id': OASIS_KEYS_FV, 'desc': 'Failure vulnerability'},
'notatrisk': {'id': OASIS_KEYS_NR, 'desc': 'Modelled but not at risk'},
'noreturn': {'id': OASIS_KEYS_XX, 'desc': 'No key returned from lookup'}
}
OASIS_UNKNOWN_ID = -1
# list of statuses classed as "modelled"
OASIS_KEYS_STATUS_MODELLED = [OASIS_KEYS_SC,OASIS_KEYS_NR]
OASIS_TASK_PN = 'PENDING'
OASIS_TASK_RN = 'RUNNING'
OASIS_TASK_SC = 'SUCCESS'
OASIS_TASK_FL = 'FAILURE'
OASIS_TASK_STATUS = {
'pending': {'id': OASIS_TASK_PN, 'desc': 'Pending'},
'running': {'id': OASIS_TASK_RN, 'desc': 'Running'},
'success': {'id': OASIS_TASK_SC, 'desc': 'Success'},
'failure': {'id': OASIS_TASK_FL, 'desc': 'Failure'}
}
| en | 0.947551 | # list of statuses classed as "modelled" | 1.949344 | 2 |
examples/set_mnist_ebm.py | bobelly/torchsupport | 18 | 6617090 | import random
import torch
import torch.nn as nn
import torch.nn.functional as func
from torch.nn.utils import spectral_norm
from torch.utils.data import Dataset
from torch.distributions import Normal
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
from torchsupport.modules.basic import MLP
from torchsupport.modules.residual import ResNetBlock2d
from torchsupport.training.samplers import Langevin
from torchsupport.training.energy import SetVAETraining
def normalize(image):
return (image - image.min()) / (image.max() - image.min())
class EnergyDataset(Dataset):
def __init__(self, data):
self.data = data
def __getitem__(self, index):
data, label_index = self.data[index]
# data = data + 0.05 * torch.rand_like(data)
label = torch.zeros(10)
label[label_index] = 1
return data, label
def __len__(self):
return len(self.data)
class MNISTSet(EnergyDataset):
def __init__(self, data, size=5):
super().__init__(data)
self.size = size
def __getitem__(self, index):
data = []
label = random.randrange(10)
for idx in range(self.size):
d, l = super().__getitem__(random.randrange(len(self)))
while l[label] < 1.0:
d, l = super().__getitem__(random.randrange(len(self)))
data.append(d.unsqueeze(0))
data = torch.cat(data, dim=0)
return data, data
class SingleEncoder(nn.Module):
def __init__(self, latents=32):
super(SingleEncoder, self).__init__()
self.block = MLP(28 * 28, latents, hidden_size=64, depth=4, batch_norm=False, normalization=spectral_norm)
def forward(self, inputs):
return self.block(inputs)
class Encoder(nn.Module):
def __init__(self, single, size=5, latents=16):
super(Encoder, self).__init__()
self.size = size
self.single = single
self.weight = spectral_norm(nn.Linear(32, 1))
self.combine = MLP(32, 32, 64, depth=3, batch_norm=False, normalization=spectral_norm)
self.mean = spectral_norm(nn.Linear(32, latents))
self.logvar = spectral_norm(nn.Linear(32, latents))
def forward(self, inputs):
inputs = inputs.view(-1, 28 * 28)
out = self.single(inputs)
weights = self.weight(out)
out = out.view(-1, self.size, 32)
weights = weights.view(-1, self.size, 1).softmax(dim=1)
pool = (weights * out).sum(dim=1)
pool = self.combine(pool)
return self.mean(pool), self.logvar(pool)
class Energy(nn.Module):
def __init__(self, sample=True):
super(Energy, self).__init__()
self.sample = sample
self.input = SingleEncoder()
self.condition = Encoder(self.input)
self.input_process = spectral_norm(nn.Linear(32, 64))
self.postprocess = spectral_norm(nn.Linear(16, 64))
self.combine = MLP(128, 1, hidden_size=64, depth=4, batch_norm=False, normalization=spectral_norm)
def forward(self, image, condition):
image = image.view(-1, 28 * 28)
out = self.input_process(self.input(image))
mean, logvar = self.condition(condition)
#distribution = Normal(mean, torch.exp(0.5 * logvar))
sample = mean + torch.randn_like(mean) * torch.exp(0.5 * logvar)#distribution.rsample()
cond = self.postprocess(sample)
cond = torch.repeat_interleave(cond, 5, dim=0)
result = self.combine(torch.cat((out, cond), dim=1))
return result, (mean, logvar)
class MNISTSetTraining(SetVAETraining):
def each_generate(self, data, *args):
ref = args[0]
samples = [sample for sample in ref.contiguous().view(-1, 1, 28, 28)[:10]]
samples = torch.cat(samples, dim=-1)
self.writer.add_image("reference", samples, self.step_id)
samples = [sample for sample in data.view(-1, 1, 28, 28)[:10]]
samples = torch.cat(samples, dim=-1)
self.writer.add_image("samples", samples, self.step_id)
if __name__ == "__main__":
mnist = MNIST("examples/", download=True, transform=ToTensor())
data = MNISTSet(mnist)
energy = Energy()
integrator = Langevin(rate=30, steps=30, max_norm=None)
training = MNISTSetTraining(
energy, data,
network_name="set-mnist-reg-noisy",
device="cuda:0",
integrator=integrator,
buffer_probability=0.95,
buffer_size=10000,
batch_size=40,
max_epochs=1000,
verbose=True
)
training.train()
| import random
import torch
import torch.nn as nn
import torch.nn.functional as func
from torch.nn.utils import spectral_norm
from torch.utils.data import Dataset
from torch.distributions import Normal
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
from torchsupport.modules.basic import MLP
from torchsupport.modules.residual import ResNetBlock2d
from torchsupport.training.samplers import Langevin
from torchsupport.training.energy import SetVAETraining
def normalize(image):
return (image - image.min()) / (image.max() - image.min())
class EnergyDataset(Dataset):
def __init__(self, data):
self.data = data
def __getitem__(self, index):
data, label_index = self.data[index]
# data = data + 0.05 * torch.rand_like(data)
label = torch.zeros(10)
label[label_index] = 1
return data, label
def __len__(self):
return len(self.data)
class MNISTSet(EnergyDataset):
def __init__(self, data, size=5):
super().__init__(data)
self.size = size
def __getitem__(self, index):
data = []
label = random.randrange(10)
for idx in range(self.size):
d, l = super().__getitem__(random.randrange(len(self)))
while l[label] < 1.0:
d, l = super().__getitem__(random.randrange(len(self)))
data.append(d.unsqueeze(0))
data = torch.cat(data, dim=0)
return data, data
class SingleEncoder(nn.Module):
def __init__(self, latents=32):
super(SingleEncoder, self).__init__()
self.block = MLP(28 * 28, latents, hidden_size=64, depth=4, batch_norm=False, normalization=spectral_norm)
def forward(self, inputs):
return self.block(inputs)
class Encoder(nn.Module):
def __init__(self, single, size=5, latents=16):
super(Encoder, self).__init__()
self.size = size
self.single = single
self.weight = spectral_norm(nn.Linear(32, 1))
self.combine = MLP(32, 32, 64, depth=3, batch_norm=False, normalization=spectral_norm)
self.mean = spectral_norm(nn.Linear(32, latents))
self.logvar = spectral_norm(nn.Linear(32, latents))
def forward(self, inputs):
inputs = inputs.view(-1, 28 * 28)
out = self.single(inputs)
weights = self.weight(out)
out = out.view(-1, self.size, 32)
weights = weights.view(-1, self.size, 1).softmax(dim=1)
pool = (weights * out).sum(dim=1)
pool = self.combine(pool)
return self.mean(pool), self.logvar(pool)
class Energy(nn.Module):
def __init__(self, sample=True):
super(Energy, self).__init__()
self.sample = sample
self.input = SingleEncoder()
self.condition = Encoder(self.input)
self.input_process = spectral_norm(nn.Linear(32, 64))
self.postprocess = spectral_norm(nn.Linear(16, 64))
self.combine = MLP(128, 1, hidden_size=64, depth=4, batch_norm=False, normalization=spectral_norm)
def forward(self, image, condition):
image = image.view(-1, 28 * 28)
out = self.input_process(self.input(image))
mean, logvar = self.condition(condition)
#distribution = Normal(mean, torch.exp(0.5 * logvar))
sample = mean + torch.randn_like(mean) * torch.exp(0.5 * logvar)#distribution.rsample()
cond = self.postprocess(sample)
cond = torch.repeat_interleave(cond, 5, dim=0)
result = self.combine(torch.cat((out, cond), dim=1))
return result, (mean, logvar)
class MNISTSetTraining(SetVAETraining):
def each_generate(self, data, *args):
ref = args[0]
samples = [sample for sample in ref.contiguous().view(-1, 1, 28, 28)[:10]]
samples = torch.cat(samples, dim=-1)
self.writer.add_image("reference", samples, self.step_id)
samples = [sample for sample in data.view(-1, 1, 28, 28)[:10]]
samples = torch.cat(samples, dim=-1)
self.writer.add_image("samples", samples, self.step_id)
if __name__ == "__main__":
mnist = MNIST("examples/", download=True, transform=ToTensor())
data = MNISTSet(mnist)
energy = Energy()
integrator = Langevin(rate=30, steps=30, max_norm=None)
training = MNISTSetTraining(
energy, data,
network_name="set-mnist-reg-noisy",
device="cuda:0",
integrator=integrator,
buffer_probability=0.95,
buffer_size=10000,
batch_size=40,
max_epochs=1000,
verbose=True
)
training.train()
| en | 0.269062 | # data = data + 0.05 * torch.rand_like(data) #distribution = Normal(mean, torch.exp(0.5 * logvar)) #distribution.rsample() | 2.337679 | 2 |
pipsource/pypi_util.py | draffensperger/pipsource | 1 | 6617091 | from typing import Optional
import json
import re
import urllib
def get_git_url(package: str) -> Optional[str]:
"""Retrieves GitHub page if specified for given PyPi package via PyPi API."""
# TODO: make sure this verifies HTTPS certs
data = urllib.request.urlopen(
'https://pypi.python.org/pypi/%s/json' % package).read()
data_parsed = json.loads(data)
info = data_parsed['info']
home_page = info.get('home_page')
if home_page.startswith('http://github.com'):
home_page = home_page.replace('http://github.com', 'https://github.com')
if re.match('^https://github.com/', home_page):
return home_page
description = info.get('description')
match = re.search('github.com\/[^\/]+/[a-zA-Z-_]+', description)
if match:
return 'https://%s' % match.group(0)
return None
| from typing import Optional
import json
import re
import urllib
def get_git_url(package: str) -> Optional[str]:
"""Retrieves GitHub page if specified for given PyPi package via PyPi API."""
# TODO: make sure this verifies HTTPS certs
data = urllib.request.urlopen(
'https://pypi.python.org/pypi/%s/json' % package).read()
data_parsed = json.loads(data)
info = data_parsed['info']
home_page = info.get('home_page')
if home_page.startswith('http://github.com'):
home_page = home_page.replace('http://github.com', 'https://github.com')
if re.match('^https://github.com/', home_page):
return home_page
description = info.get('description')
match = re.search('github.com\/[^\/]+/[a-zA-Z-_]+', description)
if match:
return 'https://%s' % match.group(0)
return None
| en | 0.309531 | Retrieves GitHub page if specified for given PyPi package via PyPi API. # TODO: make sure this verifies HTTPS certs | 3.074369 | 3 |
trust/init_trust.py | ValentinSiegert/aTLAS_host | 0 | 6617092 | <gh_stars>0
from .trust_evaluation import eval_trust
def eval_trust_with_init(agent, other_agent, current_topic, agent_behavior, scale, logger, discovery):
if agent_behavior['__init__']['name'] == 'random':
pass
eval_trust(agent, other_agent, current_topic, agent_behavior, scale, logger, discovery)
| from .trust_evaluation import eval_trust
def eval_trust_with_init(agent, other_agent, current_topic, agent_behavior, scale, logger, discovery):
if agent_behavior['__init__']['name'] == 'random':
pass
eval_trust(agent, other_agent, current_topic, agent_behavior, scale, logger, discovery) | none | 1 | 2.267197 | 2 | |
examplebook.py | georghe-crihan/epubtool | 0 | 6617093 | <reponame>georghe-crihan/epubtool
#!/usr/bin/env ng ng-jython
from glob import glob
from os.path import basename, exists, isdir, splitext, join as pathjoin
from epubtool import EPUBTool
class OWNEpub(EPUBTool):
def __init__(self, srcdir, target, cover=None):
super(OWNEpub, self).__init__(srcdir, target, cover)
self._manifest = []
self._ritems = []
self._spine = []
self._toc = []
self._images = []
self._filter_images(self.fullpath('OEBPS', 'img'))
def _filter_images(self, path):
"""Filter-out extra low-res images."""
for I in glob(pathjoin(path, '*')):
filename, ext = splitext(I)
if exists(filename + 'x' + '.gif') or \
exists(filename + 'x' + '.GIF') or \
exists(filename + 'x' + '.jpg') or \
exists(filename + 'x' + '.JPG'):
continue
self._images.append(basename(I))
def accept_file(self, F):
return True
def recursive_pack(self, Z, path, subcomp=''):
if subcomp=='img':
"""Handle images separately."""
for F in self._images:
self.write(Z, pathjoin(path, F), pathjoin('OEBPS', subcomp, F))
else:
EPUBTool.recursive_pack(self, Z, path, subcomp)
def process_content(self, overwrite, path, subcomp=''):
# Sorted index there
items = glob(pathjoin(path, '*'))
spine = []
for i in self._spine:
pj = pathjoin(path, i)
if pj in items: items.remove(pj)
spine.append(pj)
for F in spine + items:
if isdir(F):
self.process_content(overwrite, F, basename(F))
continue
if basename(F) in ['toc.ncx', 'content.opf']:
"""Already present:"""
# manifest+='''\
#<item id="ncx" href="toc.ncx"
# media-type="application/x-dtbncx+xml" />
#'''
continue
if subcomp=='img' and basename(F) not in self._images:
"""Filter-out the extra low-res images."""
continue
filename, ext = splitext(F)
if ext in ['.htm', '.html']:
mime_type='application/xhtml+xml'
self._ritems.append(len(self._manifest)+1)
self._toc.append(basename(F))
elif ext in ['.css']:
mime_type='text/css'
elif ext in ['.jpg', '.jpeg', '.JPG']:
mime_type='image/jpeg'
elif ext in ['.gif', '.GIF']:
mime_type='image/gif'
else:
mime_type=''
self._manifest.append((pathjoin(subcomp, basename(F)), mime_type))
def gen_manifest(self):
manifest=''
nitem = 1
for item in self._manifest:
if item[0]=='cover.htm':
manifest+='''\
<item id="cover" href="%s"
media-type="%s" />
''' % (item[0],item[1])
for item in self._manifest:
if item[0]=='cover.htm':
continue
manifest+='''\
<item id="item%d" href="%s"
media-type="%s" />
''' % (nitem,item[0],item[1])
nitem+=1
return manifest
def gen_guide(self):
return '''\
<reference href="cover.htm" type="cover" title="Cover" />
'''
#<reference href="cover.htm" type="text" title="Cover" />
| #!/usr/bin/env ng ng-jython
from glob import glob
from os.path import basename, exists, isdir, splitext, join as pathjoin
from epubtool import EPUBTool
class OWNEpub(EPUBTool):
def __init__(self, srcdir, target, cover=None):
super(OWNEpub, self).__init__(srcdir, target, cover)
self._manifest = []
self._ritems = []
self._spine = []
self._toc = []
self._images = []
self._filter_images(self.fullpath('OEBPS', 'img'))
def _filter_images(self, path):
"""Filter-out extra low-res images."""
for I in glob(pathjoin(path, '*')):
filename, ext = splitext(I)
if exists(filename + 'x' + '.gif') or \
exists(filename + 'x' + '.GIF') or \
exists(filename + 'x' + '.jpg') or \
exists(filename + 'x' + '.JPG'):
continue
self._images.append(basename(I))
def accept_file(self, F):
return True
def recursive_pack(self, Z, path, subcomp=''):
if subcomp=='img':
"""Handle images separately."""
for F in self._images:
self.write(Z, pathjoin(path, F), pathjoin('OEBPS', subcomp, F))
else:
EPUBTool.recursive_pack(self, Z, path, subcomp)
def process_content(self, overwrite, path, subcomp=''):
# Sorted index there
items = glob(pathjoin(path, '*'))
spine = []
for i in self._spine:
pj = pathjoin(path, i)
if pj in items: items.remove(pj)
spine.append(pj)
for F in spine + items:
if isdir(F):
self.process_content(overwrite, F, basename(F))
continue
if basename(F) in ['toc.ncx', 'content.opf']:
"""Already present:"""
# manifest+='''\
#<item id="ncx" href="toc.ncx"
# media-type="application/x-dtbncx+xml" />
#'''
continue
if subcomp=='img' and basename(F) not in self._images:
"""Filter-out the extra low-res images."""
continue
filename, ext = splitext(F)
if ext in ['.htm', '.html']:
mime_type='application/xhtml+xml'
self._ritems.append(len(self._manifest)+1)
self._toc.append(basename(F))
elif ext in ['.css']:
mime_type='text/css'
elif ext in ['.jpg', '.jpeg', '.JPG']:
mime_type='image/jpeg'
elif ext in ['.gif', '.GIF']:
mime_type='image/gif'
else:
mime_type=''
self._manifest.append((pathjoin(subcomp, basename(F)), mime_type))
def gen_manifest(self):
manifest=''
nitem = 1
for item in self._manifest:
if item[0]=='cover.htm':
manifest+='''\
<item id="cover" href="%s"
media-type="%s" />
''' % (item[0],item[1])
for item in self._manifest:
if item[0]=='cover.htm':
continue
manifest+='''\
<item id="item%d" href="%s"
media-type="%s" />
''' % (nitem,item[0],item[1])
nitem+=1
return manifest
def gen_guide(self):
return '''\
<reference href="cover.htm" type="cover" title="Cover" />
'''
#<reference href="cover.htm" type="text" title="Cover" /> | en | 0.286554 | #!/usr/bin/env ng ng-jython Filter-out extra low-res images. Handle images separately. # Sorted index there Already present: # manifest+='''\ #<item id="ncx" href="toc.ncx" # media-type="application/x-dtbncx+xml" /> #''' Filter-out the extra low-res images. \ <item id="cover" href="%s" media-type="%s" /> \ <item id="item%d" href="%s" media-type="%s" /> \ <reference href="cover.htm" type="cover" title="Cover" /> #<reference href="cover.htm" type="text" title="Cover" /> | 2.838347 | 3 |
python/test/test_isbn_methods.py | sma-h/openapc-de | 89 | 6617094 | <gh_stars>10-100
# -*- coding: UTF-8 -*-
import os
from sys import path
from urllib.request import urlretrieve
import pytest
path.append(os.path.join(path[0], "python"))
import openapc_toolkit as oat
CORRECT_ISBN_SPLITS = {
"9782753518278": "978-2-7535-1827-8",
"9780815726890": "978-0-8157-2689-0",
"9788496820524": "978-84-96820-52-4",
"9783837633269": "978-3-8376-3326-9",
"9781947172395": "978-1-947172-39-5",
"9788877137531": "978-88-7713-753-1",
"9789289342582": "978-92-893-4258-2",
"9789932021789": "978-9932-02-178-9",
"9780472131792": "978-0-472-13179-2"
}
INVALID_ISBNS = [
"97827535182784", # too long
"978275351827", # too short
"978275351827A", # not all digits
"9772753518278", # invalid EAN prefix
"9786712345678", # undefined registration group range for prefix 978
"9786219123456" # undefined registrant range (9xxxxxx) for registration group 978-621 (Philippines)
]
INVALID_CHECK_DIGITS = [
"9782753518279",
"9780815726892",
"9788496820523",
"9783837633265",
"9781947172399",
"9788877137530",
"9789289342588",
"9789932021783"
]
NORMALIZATION_TESTS = {
"978-1-4780-0716-6": { # valid split
"valid": True,
"input_value": "978-1-4780-0716-6",
"normalised": "978-1-4780-0716-6"
},
"9783848760510": { # valid unsplit
"valid": True,
"input_value": "9783848760510",
"normalised": "978-3-8487-6051-0"
},
"978-10-4780-0716-6": { # invalid split, too long
"valid": False,
"input_value": "978-10-4780-0716-6",
"error_type": 2
},
"978-1-478-0716-6": { # invalid split, too short
"valid": False,
"input_value": "978-1-478-0716-6",
"error_type": 1
},
"978-14-780-0716-6": { # invalid split, wrong segmenation
"valid": False,
"input_value": "978-14-780-0716-6",
"error_type": 3
},
"97838487605109": { # invalid unsplit, too long
"valid": False,
"input_value": "97838487605109",
"error_type": 0
},
}
@pytest.fixture(scope="module")
def isbn_handling():
index = 0
tempfile_name = "TempRangeMessage.xml"
while os.path.isfile(tempfile_name):
index += 1
tempfile_name = "TempRangeMessage_" + str(index) + ".xml"
print('\nUsing temporary RangeMessage file path "' + tempfile_name + '"...')
yield oat.ISBNHandling(tempfile_name)
print('\nRemoving temporary RangeMessage file "' + tempfile_name + '"...')
os.remove(tempfile_name)
@pytest.mark.parametrize("isbn, split_result", CORRECT_ISBN_SPLITS.items())
def test_isbn_splits(isbn, split_result, isbn_handling):
result = isbn_handling.split_isbn(isbn)
assert result["success"] == True
assert result["value"] == split_result
@pytest.mark.parametrize("invalid_isbn", INVALID_ISBNS)
def test_isbn_split_fails(invalid_isbn, isbn_handling):
result = isbn_handling.split_isbn(invalid_isbn)
assert result["success"] == False
@pytest.mark.parametrize("isbn", CORRECT_ISBN_SPLITS.keys())
def test_valid_check_digits(isbn, isbn_handling):
assert isbn_handling.isbn_has_valid_check_digit(isbn)
@pytest.mark.parametrize("isbn", INVALID_CHECK_DIGITS)
def test_invalid_check_digits(isbn, isbn_handling):
assert not isbn_handling.isbn_has_valid_check_digit(isbn)
@pytest.mark.parametrize("isbn, expected_result", NORMALIZATION_TESTS.items())
def test_normalization(isbn, expected_result, isbn_handling):
result = isbn_handling.test_and_normalize_isbn(isbn)
assert set(result.keys()) == set(expected_result.keys())
for key in result:
assert result[key] == expected_result[key]
| # -*- coding: UTF-8 -*-
import os
from sys import path
from urllib.request import urlretrieve
import pytest
path.append(os.path.join(path[0], "python"))
import openapc_toolkit as oat
CORRECT_ISBN_SPLITS = {
"9782753518278": "978-2-7535-1827-8",
"9780815726890": "978-0-8157-2689-0",
"9788496820524": "978-84-96820-52-4",
"9783837633269": "978-3-8376-3326-9",
"9781947172395": "978-1-947172-39-5",
"9788877137531": "978-88-7713-753-1",
"9789289342582": "978-92-893-4258-2",
"9789932021789": "978-9932-02-178-9",
"9780472131792": "978-0-472-13179-2"
}
INVALID_ISBNS = [
"97827535182784", # too long
"978275351827", # too short
"978275351827A", # not all digits
"9772753518278", # invalid EAN prefix
"9786712345678", # undefined registration group range for prefix 978
"9786219123456" # undefined registrant range (9xxxxxx) for registration group 978-621 (Philippines)
]
INVALID_CHECK_DIGITS = [
"9782753518279",
"9780815726892",
"9788496820523",
"9783837633265",
"9781947172399",
"9788877137530",
"9789289342588",
"9789932021783"
]
NORMALIZATION_TESTS = {
"978-1-4780-0716-6": { # valid split
"valid": True,
"input_value": "978-1-4780-0716-6",
"normalised": "978-1-4780-0716-6"
},
"9783848760510": { # valid unsplit
"valid": True,
"input_value": "9783848760510",
"normalised": "978-3-8487-6051-0"
},
"978-10-4780-0716-6": { # invalid split, too long
"valid": False,
"input_value": "978-10-4780-0716-6",
"error_type": 2
},
"978-1-478-0716-6": { # invalid split, too short
"valid": False,
"input_value": "978-1-478-0716-6",
"error_type": 1
},
"978-14-780-0716-6": { # invalid split, wrong segmenation
"valid": False,
"input_value": "978-14-780-0716-6",
"error_type": 3
},
"97838487605109": { # invalid unsplit, too long
"valid": False,
"input_value": "97838487605109",
"error_type": 0
},
}
@pytest.fixture(scope="module")
def isbn_handling():
index = 0
tempfile_name = "TempRangeMessage.xml"
while os.path.isfile(tempfile_name):
index += 1
tempfile_name = "TempRangeMessage_" + str(index) + ".xml"
print('\nUsing temporary RangeMessage file path "' + tempfile_name + '"...')
yield oat.ISBNHandling(tempfile_name)
print('\nRemoving temporary RangeMessage file "' + tempfile_name + '"...')
os.remove(tempfile_name)
@pytest.mark.parametrize("isbn, split_result", CORRECT_ISBN_SPLITS.items())
def test_isbn_splits(isbn, split_result, isbn_handling):
result = isbn_handling.split_isbn(isbn)
assert result["success"] == True
assert result["value"] == split_result
@pytest.mark.parametrize("invalid_isbn", INVALID_ISBNS)
def test_isbn_split_fails(invalid_isbn, isbn_handling):
result = isbn_handling.split_isbn(invalid_isbn)
assert result["success"] == False
@pytest.mark.parametrize("isbn", CORRECT_ISBN_SPLITS.keys())
def test_valid_check_digits(isbn, isbn_handling):
assert isbn_handling.isbn_has_valid_check_digit(isbn)
@pytest.mark.parametrize("isbn", INVALID_CHECK_DIGITS)
def test_invalid_check_digits(isbn, isbn_handling):
assert not isbn_handling.isbn_has_valid_check_digit(isbn)
@pytest.mark.parametrize("isbn, expected_result", NORMALIZATION_TESTS.items())
def test_normalization(isbn, expected_result, isbn_handling):
result = isbn_handling.test_and_normalize_isbn(isbn)
assert set(result.keys()) == set(expected_result.keys())
for key in result:
assert result[key] == expected_result[key] | en | 0.445182 | # -*- coding: UTF-8 -*- # too long # too short # not all digits # invalid EAN prefix # undefined registration group range for prefix 978 # undefined registrant range (9xxxxxx) for registration group 978-621 (Philippines) # valid split # valid unsplit # invalid split, too long # invalid split, too short # invalid split, wrong segmenation # invalid unsplit, too long | 2.425502 | 2 |
app/reports/views.py | alexandre-hirata/qualiCar | 0 | 6617095 | <reponame>alexandre-hirata/qualiCar
from django.shortcuts import render
from django.http import HttpResponse
from tablib import Dataset
from json2xml import json2xml
from json2xml.utils import readfromstring
import logging
from reports.resources import PartResource
from qualiCar_API.models import Part
# Get a logging instance
logger = logging.getLogger (__name__)
def export_data (request):
logger.info (" ** Reports -> views.export_data method")
if request.method == 'POST':
logger.info (" ** POST method")
# Get option from form
file_format = request.POST ['file-format']
part_resource = PartResource ()
dataset = part_resource.export ()
if file_format == 'CSV':
logger.info (" ** Generate CSV file...")
response = HttpResponse (dataset.csv, content_type='text/csv')
response ['Content-Disposition'] = 'attachment; filename="part_exported_data.csv"'
return response
elif file_format == 'JSON':
logger.info (" ** Generate JSON file...")
response = HttpResponse (dataset.json, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename="part_exported_data.json"'
return response
elif file_format == 'XLS':
logger.info (" ** Generate XLS file...")
response = HttpResponse (dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="part_exported_data.xls"'
return response
elif file_format == 'XML':
logger.info (" ** Generate XML file...")
# This step is using json2xml library
# To do so, the code converts to JSON to convert (again) to XML
logger.info (" ** Convert to XML file using json2xml...")
xml_output = json2xml.Json2xml (readfromstring (dataset.json)).to_xml()
response = HttpResponse (xml_output, content_type='application/xml')
response['Content-Disposition'] = 'attachment; filename="part_exported_data.xml"'
return response
return render (request, 'forms/export.html')
def import_data(request):
logger.info (" ** Reports -> views.import_data method")
if request.method == 'POST':
logger.info (" ** POST method")
# Get option from form
file_format = request.POST ['file-format']
part_resource = PartResource ()
dataset = Dataset ()
new_part = request.FILES['importData']
if file_format == 'CSV':
logger.info (" ** Import CSV file option...")
imported_data = dataset.load (new_part.read().decode('utf-8'),format='csv')
# Testing data import
logger.info (" ** Test CSV file import...")
result = part_resource.import_data (dataset, dry_run = True)
elif file_format == 'JSON':
logger.info (" ** Import JSON file option...")
imported_data = dataset.load (new_part.read().decode('utf-8'),format='json')
# Testing data import
logger.info (" ** Test JSON file import...")
result = part_resource.import_data (dataset, dry_run = True)
if not result.has_errors():
logger.info (" ** No errors. Import %s file...", file_format)
# Import now
part_resource.import_data (dataset, dry_run = False)
return render(request, 'forms/import.html')
| from django.shortcuts import render
from django.http import HttpResponse
from tablib import Dataset
from json2xml import json2xml
from json2xml.utils import readfromstring
import logging
from reports.resources import PartResource
from qualiCar_API.models import Part
# Get a logging instance
logger = logging.getLogger (__name__)
def export_data (request):
logger.info (" ** Reports -> views.export_data method")
if request.method == 'POST':
logger.info (" ** POST method")
# Get option from form
file_format = request.POST ['file-format']
part_resource = PartResource ()
dataset = part_resource.export ()
if file_format == 'CSV':
logger.info (" ** Generate CSV file...")
response = HttpResponse (dataset.csv, content_type='text/csv')
response ['Content-Disposition'] = 'attachment; filename="part_exported_data.csv"'
return response
elif file_format == 'JSON':
logger.info (" ** Generate JSON file...")
response = HttpResponse (dataset.json, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename="part_exported_data.json"'
return response
elif file_format == 'XLS':
logger.info (" ** Generate XLS file...")
response = HttpResponse (dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="part_exported_data.xls"'
return response
elif file_format == 'XML':
logger.info (" ** Generate XML file...")
# This step is using json2xml library
# To do so, the code converts to JSON to convert (again) to XML
logger.info (" ** Convert to XML file using json2xml...")
xml_output = json2xml.Json2xml (readfromstring (dataset.json)).to_xml()
response = HttpResponse (xml_output, content_type='application/xml')
response['Content-Disposition'] = 'attachment; filename="part_exported_data.xml"'
return response
return render (request, 'forms/export.html')
def import_data(request):
logger.info (" ** Reports -> views.import_data method")
if request.method == 'POST':
logger.info (" ** POST method")
# Get option from form
file_format = request.POST ['file-format']
part_resource = PartResource ()
dataset = Dataset ()
new_part = request.FILES['importData']
if file_format == 'CSV':
logger.info (" ** Import CSV file option...")
imported_data = dataset.load (new_part.read().decode('utf-8'),format='csv')
# Testing data import
logger.info (" ** Test CSV file import...")
result = part_resource.import_data (dataset, dry_run = True)
elif file_format == 'JSON':
logger.info (" ** Import JSON file option...")
imported_data = dataset.load (new_part.read().decode('utf-8'),format='json')
# Testing data import
logger.info (" ** Test JSON file import...")
result = part_resource.import_data (dataset, dry_run = True)
if not result.has_errors():
logger.info (" ** No errors. Import %s file...", file_format)
# Import now
part_resource.import_data (dataset, dry_run = False)
return render(request, 'forms/import.html') | en | 0.677091 | # Get a logging instance # Get option from form # This step is using json2xml library # To do so, the code converts to JSON to convert (again) to XML # Get option from form # Testing data import # Testing data import # Import now | 2.255763 | 2 |
sales/__openerp__.py | oldrev/odoodev-demo-2014 | 2 | 6617096 | #encoding: utf-8
{
'name': u'销售订单管理开发实例', #模块名称,必填
'version': '0.1', #版本
'depends': ['base', 'web'], #依赖的模块
'category' : 'Demo', #模块分类
'summary': 'Odoo 简单模块开发例子:销售订单管理', #模块简介
'description': """""", #模块描述
'author': 'YourName', #作者
'website': 'http://www.sandwych.com', #
'data': [
'sales_view.xml', #初始化模块或者升级模块时导入的数据
],
'demo': [], #这里指定演示数据
'installable': True, #模块是否可通过管理界面安装
'images': [], #指定模块的图标等
}
| #encoding: utf-8
{
'name': u'销售订单管理开发实例', #模块名称,必填
'version': '0.1', #版本
'depends': ['base', 'web'], #依赖的模块
'category' : 'Demo', #模块分类
'summary': 'Odoo 简单模块开发例子:销售订单管理', #模块简介
'description': """""", #模块描述
'author': 'YourName', #作者
'website': 'http://www.sandwych.com', #
'data': [
'sales_view.xml', #初始化模块或者升级模块时导入的数据
],
'demo': [], #这里指定演示数据
'installable': True, #模块是否可通过管理界面安装
'images': [], #指定模块的图标等
}
| zh | 0.937812 | #encoding: utf-8 #模块名称,必填 #版本 #依赖的模块 #模块分类 #模块简介 #模块描述 #作者 # #初始化模块或者升级模块时导入的数据 #这里指定演示数据 #模块是否可通过管理界面安装 #指定模块的图标等 | 1.217389 | 1 |
experiments/AB_choice_experiment_stim_generation.py | cogtoolslab/projection_block_construction | 0 | 6617097 | <filename>experiments/AB_choice_experiment_stim_generation.py
# %% [markdown]
# # Generating stimuli for A/B choice experiment
# %% [markdown]
# Purpose of this notebook is:
# * to create a set of towers
# * for each tower, create a tree of branching subgoal choices, which each subgoal on each turn being either the cheapest or the most expensive one meeting a certain condition.
# * ensuring that each node has a path to the goal (can we do that?)
# * visualize the different choices
#
# Requires:
# *
#
# See also:
# *
# %% [markdown]
# ## Setup
# %%
# set up imports
import os
import sys
__file__ = os.getcwd()
proj_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(proj_dir)
utils_dir = os.path.join(proj_dir, 'utils')
sys.path.append(utils_dir)
analysis_dir = os.path.join(proj_dir, 'analysis')
analysis_utils_dir = os.path.join(analysis_dir, 'utils')
sys.path.append(analysis_utils_dir)
agent_dir = os.path.join(proj_dir, 'model')
sys.path.append(agent_dir)
agent_util_dir = os.path.join(agent_dir, 'utils')
sys.path.append(agent_util_dir)
experiments_dir = os.path.join(proj_dir, 'experiments')
sys.path.append(experiments_dir)
df_dir = os.path.join(proj_dir, 'results/dataframes')
stim_dir = os.path.join(proj_dir, 'stimuli')
# %%
import stimuli.tower_generator as tower_generator
from tqdm import tqdm
import p_tqdm
import pickle
import math
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import scipy.stats as stats
from scipy.stats import sem as sem
from utils.blockworld_library import *
from utils.blockworld import *
from model.BFS_Lookahead_Agent import BFS_Lookahead_Agent
from model.BFS_Agent import BFS_Agent
from model.Astar_Agent import Astar_Agent
from model.Best_First_Search_Agent import Best_First_Search_Agent
from model.Subgoal_Planning_Agent import Subgoal_Planning_Agent
from model.utils.decomposition_functions import *
import utils.blockworld_library as bl
# %%
# show all columns in dataframe
pd.set_option('display.max_columns', None)
# %% [markdown]
# ## Generating towers
#
# %%
block_library = bl_nonoverlapping_simple
# %%
generator = tower_generator.TowerGenerator(8, 8,
block_library=block_library,
seed=42,
padding=(2, 0),
num_blocks=lambda: random.randint(4, 10), # flat random interval of tower sizes (inclusive)
)
# %%
NUM_TOWERS = 64
towers = []
for i in tqdm(range(NUM_TOWERS)):
towers.append(generator.generate())
# %%
worlds = [Blockworld(silhouette=t['bitmap'], block_library=bl.bl_nonoverlapping_simple) for t in towers]
# %% [markdown]
# ### Visualize the generated towers
# %%
# look at towers
def visualize_towers(towers, text_parameters=None):
fig,axes = plt.subplots(math.ceil(len(towers)/5),5,figsize=(20,15*math.ceil(len(towers)/20)))
for axis, tower in zip(axes.flatten(),towers):
axis.imshow(tower['bitmap']*1.0)
if text_parameters is not None:
if type(text_parameters) is not list:
text_parameters = [text_parameters]
for y_offset,text_parameter in enumerate(text_parameters):
axis.text(0,y_offset*1.,str(text_parameter+": "+str(tower[text_parameter])),color='gray',fontsize=20)
plt.tight_layout()
plt.show()
# %%
# visualize_towers(towers)
# %% [markdown]
# ## Score towers for basic difficulty
# For each tower, compute the cost of solving it using a planning agent.
# %% [markdown]
# Here, we use Best First Search without lookahead or subgoals.
# %%
lower_agent = Best_First_Search_Agent(random_seed=42)
# %%
def get_tower_cost(agent,world):
cost = 0
agent.set_world(world)
world.reset()
while world.status()[0] == 'Ongoing':
_,step_info = agent.act()
cost += step_info['states_evaluated']
return cost,world.status()
# %%
costs = []
statusses = []
for world in tqdm(worlds):
cost,status = get_tower_cost(lower_agent,world)
costs.append(cost)
statusses.append(status)
# %% [markdown]
# Split the basic costs into three percentiles: easy, medium, hard.
# %%
difficulty_percentiles = [np.percentile(costs, i)
for i in [33, 66, 99]]
percentiles = [None] * len(costs)
for i, cost in enumerate(costs):
if cost < difficulty_percentiles[0]:
percentiles[i] = 'easy'
elif cost < difficulty_percentiles[1]:
percentiles[i] = 'medium'
else:
percentiles[i] = 'hard'
# %% [markdown]
# ## Find best and worst sequence of subgoals for each tower
# We compute the full subgoal tree for each tower and extract the best and worst sequence.
# %%
decomposer = Rectangular_Keyholes(
sequence_length=4,
necessary_conditions=[
Area_larger_than(area=1),
Area_smaller_than(area=21),
No_edge_rows_or_columns(),
],
necessary_sequence_conditions=[
Complete(),
No_overlap(),
Supported(),
]
)
sg_agent = Subgoal_Planning_Agent(lower_agent=lower_agent,
random_seed=42,
decomposer=decomposer)
# %% [markdown]
# Calculate the subgoal tree for each tower.
#
# Sadly, the sockets seem to make this hard to parallelize.
# %%
# # parallelized—does not presently work (somehow the sockets in p_tqdm just don't work)
# def get_subgoal_tree_from_tower(agent, world):
# agent.set_world(world)
# return agent.get_subgoal_tree()
# agents = [copy.deepcopy(a) for a in [sg_agent]*len(worlds)]
# trees = p_tqdm.p_map(get_subgoal_tree_from_tower, agents, worlds)
# %%
# sequential version
trees = []
for world in tqdm(worlds):
world.reset()
sg_agent.set_world(world)
trees.append(sg_agent.get_subgoal_tree())
# %% [markdown]
# Visualize the best and worst sequence of subgoals for each tower.
# %%
for i, tree in enumerate(trees):
print("Tower {}".format(i))
best_seq = tree.get_best_sequence()
try:
print("Best sequence with cost",best_seq.solution_cost(),"for tower",i)
except:
print("No Best sequence for tower",i)
worst_seq = tree.get_worst_sequence()
try:
print("Worst sequence with cost",worst_seq.solution_cost(),"for tower",i)
except:
print("No Worst sequence for tower",i)
# %% [markdown]
# Let's save out everything
# %%
results = [{'world':world,'subgoal tree':tree,'cost':cost,'percentile':percentile} for world,tree,cost,percentile in zip(worlds,trees,costs,percentiles)]
# %%
pickle.dump(results, open("AB_choice subgoal results.pkl", "wb"))
# %%
| <filename>experiments/AB_choice_experiment_stim_generation.py
# %% [markdown]
# # Generating stimuli for A/B choice experiment
# %% [markdown]
# Purpose of this notebook is:
# * to create a set of towers
# * for each tower, create a tree of branching subgoal choices, which each subgoal on each turn being either the cheapest or the most expensive one meeting a certain condition.
# * ensuring that each node has a path to the goal (can we do that?)
# * visualize the different choices
#
# Requires:
# *
#
# See also:
# *
# %% [markdown]
# ## Setup
# %%
# set up imports
import os
import sys
__file__ = os.getcwd()
proj_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(proj_dir)
utils_dir = os.path.join(proj_dir, 'utils')
sys.path.append(utils_dir)
analysis_dir = os.path.join(proj_dir, 'analysis')
analysis_utils_dir = os.path.join(analysis_dir, 'utils')
sys.path.append(analysis_utils_dir)
agent_dir = os.path.join(proj_dir, 'model')
sys.path.append(agent_dir)
agent_util_dir = os.path.join(agent_dir, 'utils')
sys.path.append(agent_util_dir)
experiments_dir = os.path.join(proj_dir, 'experiments')
sys.path.append(experiments_dir)
df_dir = os.path.join(proj_dir, 'results/dataframes')
stim_dir = os.path.join(proj_dir, 'stimuli')
# %%
import stimuli.tower_generator as tower_generator
from tqdm import tqdm
import p_tqdm
import pickle
import math
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import scipy.stats as stats
from scipy.stats import sem as sem
from utils.blockworld_library import *
from utils.blockworld import *
from model.BFS_Lookahead_Agent import BFS_Lookahead_Agent
from model.BFS_Agent import BFS_Agent
from model.Astar_Agent import Astar_Agent
from model.Best_First_Search_Agent import Best_First_Search_Agent
from model.Subgoal_Planning_Agent import Subgoal_Planning_Agent
from model.utils.decomposition_functions import *
import utils.blockworld_library as bl
# %%
# show all columns in dataframe
pd.set_option('display.max_columns', None)
# %% [markdown]
# ## Generating towers
#
# %%
block_library = bl_nonoverlapping_simple
# %%
generator = tower_generator.TowerGenerator(8, 8,
block_library=block_library,
seed=42,
padding=(2, 0),
num_blocks=lambda: random.randint(4, 10), # flat random interval of tower sizes (inclusive)
)
# %%
NUM_TOWERS = 64
towers = []
for i in tqdm(range(NUM_TOWERS)):
towers.append(generator.generate())
# %%
worlds = [Blockworld(silhouette=t['bitmap'], block_library=bl.bl_nonoverlapping_simple) for t in towers]
# %% [markdown]
# ### Visualize the generated towers
# %%
# look at towers
def visualize_towers(towers, text_parameters=None):
fig,axes = plt.subplots(math.ceil(len(towers)/5),5,figsize=(20,15*math.ceil(len(towers)/20)))
for axis, tower in zip(axes.flatten(),towers):
axis.imshow(tower['bitmap']*1.0)
if text_parameters is not None:
if type(text_parameters) is not list:
text_parameters = [text_parameters]
for y_offset,text_parameter in enumerate(text_parameters):
axis.text(0,y_offset*1.,str(text_parameter+": "+str(tower[text_parameter])),color='gray',fontsize=20)
plt.tight_layout()
plt.show()
# %%
# visualize_towers(towers)
# %% [markdown]
# ## Score towers for basic difficulty
# For each tower, compute the cost of solving it using a planning agent.
# %% [markdown]
# Here, we use Best First Search without lookahead or subgoals.
# %%
lower_agent = Best_First_Search_Agent(random_seed=42)
# %%
def get_tower_cost(agent,world):
cost = 0
agent.set_world(world)
world.reset()
while world.status()[0] == 'Ongoing':
_,step_info = agent.act()
cost += step_info['states_evaluated']
return cost,world.status()
# %%
costs = []
statusses = []
for world in tqdm(worlds):
cost,status = get_tower_cost(lower_agent,world)
costs.append(cost)
statusses.append(status)
# %% [markdown]
# Split the basic costs into three percentiles: easy, medium, hard.
# %%
difficulty_percentiles = [np.percentile(costs, i)
for i in [33, 66, 99]]
percentiles = [None] * len(costs)
for i, cost in enumerate(costs):
if cost < difficulty_percentiles[0]:
percentiles[i] = 'easy'
elif cost < difficulty_percentiles[1]:
percentiles[i] = 'medium'
else:
percentiles[i] = 'hard'
# %% [markdown]
# ## Find best and worst sequence of subgoals for each tower
# We compute the full subgoal tree for each tower and extract the best and worst sequence.
# %%
decomposer = Rectangular_Keyholes(
sequence_length=4,
necessary_conditions=[
Area_larger_than(area=1),
Area_smaller_than(area=21),
No_edge_rows_or_columns(),
],
necessary_sequence_conditions=[
Complete(),
No_overlap(),
Supported(),
]
)
sg_agent = Subgoal_Planning_Agent(lower_agent=lower_agent,
random_seed=42,
decomposer=decomposer)
# %% [markdown]
# Calculate the subgoal tree for each tower.
#
# Sadly, the sockets seem to make this hard to parallelize.
# %%
# # parallelized—does not presently work (somehow the sockets in p_tqdm just don't work)
# def get_subgoal_tree_from_tower(agent, world):
# agent.set_world(world)
# return agent.get_subgoal_tree()
# agents = [copy.deepcopy(a) for a in [sg_agent]*len(worlds)]
# trees = p_tqdm.p_map(get_subgoal_tree_from_tower, agents, worlds)
# %%
# sequential version
trees = []
for world in tqdm(worlds):
world.reset()
sg_agent.set_world(world)
trees.append(sg_agent.get_subgoal_tree())
# %% [markdown]
# Visualize the best and worst sequence of subgoals for each tower.
# %%
for i, tree in enumerate(trees):
print("Tower {}".format(i))
best_seq = tree.get_best_sequence()
try:
print("Best sequence with cost",best_seq.solution_cost(),"for tower",i)
except:
print("No Best sequence for tower",i)
worst_seq = tree.get_worst_sequence()
try:
print("Worst sequence with cost",worst_seq.solution_cost(),"for tower",i)
except:
print("No Worst sequence for tower",i)
# %% [markdown]
# Let's save out everything
# %%
results = [{'world':world,'subgoal tree':tree,'cost':cost,'percentile':percentile} for world,tree,cost,percentile in zip(worlds,trees,costs,percentiles)]
# %%
pickle.dump(results, open("AB_choice subgoal results.pkl", "wb"))
# %%
| en | 0.769569 | # %% [markdown] # # Generating stimuli for A/B choice experiment # %% [markdown] # Purpose of this notebook is: # * to create a set of towers # * for each tower, create a tree of branching subgoal choices, which each subgoal on each turn being either the cheapest or the most expensive one meeting a certain condition. # * ensuring that each node has a path to the goal (can we do that?) # * visualize the different choices # # Requires: # * # # See also: # * # %% [markdown] # ## Setup # %% # set up imports # %% # %% # show all columns in dataframe # %% [markdown] # ## Generating towers # # %% # %% # flat random interval of tower sizes (inclusive) # %% # %% # %% [markdown] # ### Visualize the generated towers # %% # look at towers # %% # visualize_towers(towers) # %% [markdown] # ## Score towers for basic difficulty # For each tower, compute the cost of solving it using a planning agent. # %% [markdown] # Here, we use Best First Search without lookahead or subgoals. # %% # %% # %% # %% [markdown] # Split the basic costs into three percentiles: easy, medium, hard. # %% # %% [markdown] # ## Find best and worst sequence of subgoals for each tower # We compute the full subgoal tree for each tower and extract the best and worst sequence. # %% # %% [markdown] # Calculate the subgoal tree for each tower. # # Sadly, the sockets seem to make this hard to parallelize. # %% # # parallelized—does not presently work (somehow the sockets in p_tqdm just don't work) # def get_subgoal_tree_from_tower(agent, world): # agent.set_world(world) # return agent.get_subgoal_tree() # agents = [copy.deepcopy(a) for a in [sg_agent]*len(worlds)] # trees = p_tqdm.p_map(get_subgoal_tree_from_tower, agents, worlds) # %% # sequential version # %% [markdown] # Visualize the best and worst sequence of subgoals for each tower. # %% # %% [markdown] # Let's save out everything # %% # %% # %% | 2.484665 | 2 |
sos_trades_core/execution_engine/data_connector/data_connector_factory.py | os-climate/sostrades-core | 8 | 6617098 | '''
Copyright 2022 Airbus SAS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
from sos_trades_core.execution_engine.data_connector.dremio_data_connector import DremioDataConnector
from sos_trades_core.execution_engine.data_connector.trino_data_connector import TrinoDataConnector
from sos_trades_core.execution_engine.data_connector.mock_connector import MockConnector
from sos_trades_core.execution_engine.data_connector.ontology_data_connector import OntologyDataConnector
class ConnectorFactory:
"""
Data connector factory
"""
CONNECTOR_TYPE = 'connector_type'
CONNECTORS = {
DremioDataConnector.NAME: DremioDataConnector,
MockConnector.NAME: MockConnector,
TrinoDataConnector.NAME: TrinoDataConnector,
OntologyDataConnector.NAME: OntologyDataConnector
}
@staticmethod
def set_connector_request(connector_info, request):
if ConnectorFactory.CONNECTOR_TYPE in connector_info:
connector_instance = ConnectorFactory.CONNECTORS[connector_info[ConnectorFactory.CONNECTOR_TYPE]](
)
connector_instance.set_connector_request(connector_info, request)
else:
raise TypeError(f'Connector type not found in {connector_info}')
return connector_info
"""
@staticmethod
def get_connector(connector_identifier):
return ConnectorFactory.CONNECTORS[connector_identifier]()
"""
@staticmethod
def use_data_connector(connector_info, logger=None):
"""
create and instance of the required data connector
:params: connector_info, information with for connection and request
:type: dict
"""
new_connector = None
if ConnectorFactory.CONNECTOR_TYPE in connector_info:
new_connector = ConnectorFactory.CONNECTORS[connector_info[ConnectorFactory.CONNECTOR_TYPE]](
)
else:
raise TypeError(f'Connector type not found in {connector_info}')
try:
if new_connector.get_connector_mode(connector_info) == new_connector.CONNECTOR_MODE_READ:
data = new_connector.load_data(connector_info)
else:
data = new_connector.write_data(connector_info)
except Exception as exp:
str_error = f'Error while using data connector {connector_info[ConnectorFactory.CONNECTOR_TYPE]}: {str(exp)}'
if logger is not None:
logger.error(str_error)
raise Exception(str_error)
return data
| '''
Copyright 2022 Airbus SAS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
from sos_trades_core.execution_engine.data_connector.dremio_data_connector import DremioDataConnector
from sos_trades_core.execution_engine.data_connector.trino_data_connector import TrinoDataConnector
from sos_trades_core.execution_engine.data_connector.mock_connector import MockConnector
from sos_trades_core.execution_engine.data_connector.ontology_data_connector import OntologyDataConnector
class ConnectorFactory:
"""
Data connector factory
"""
CONNECTOR_TYPE = 'connector_type'
CONNECTORS = {
DremioDataConnector.NAME: DremioDataConnector,
MockConnector.NAME: MockConnector,
TrinoDataConnector.NAME: TrinoDataConnector,
OntologyDataConnector.NAME: OntologyDataConnector
}
@staticmethod
def set_connector_request(connector_info, request):
if ConnectorFactory.CONNECTOR_TYPE in connector_info:
connector_instance = ConnectorFactory.CONNECTORS[connector_info[ConnectorFactory.CONNECTOR_TYPE]](
)
connector_instance.set_connector_request(connector_info, request)
else:
raise TypeError(f'Connector type not found in {connector_info}')
return connector_info
"""
@staticmethod
def get_connector(connector_identifier):
return ConnectorFactory.CONNECTORS[connector_identifier]()
"""
@staticmethod
def use_data_connector(connector_info, logger=None):
"""
create and instance of the required data connector
:params: connector_info, information with for connection and request
:type: dict
"""
new_connector = None
if ConnectorFactory.CONNECTOR_TYPE in connector_info:
new_connector = ConnectorFactory.CONNECTORS[connector_info[ConnectorFactory.CONNECTOR_TYPE]](
)
else:
raise TypeError(f'Connector type not found in {connector_info}')
try:
if new_connector.get_connector_mode(connector_info) == new_connector.CONNECTOR_MODE_READ:
data = new_connector.load_data(connector_info)
else:
data = new_connector.write_data(connector_info)
except Exception as exp:
str_error = f'Error while using data connector {connector_info[ConnectorFactory.CONNECTOR_TYPE]}: {str(exp)}'
if logger is not None:
logger.error(str_error)
raise Exception(str_error)
return data
| en | 0.762713 | Copyright 2022 Airbus SAS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Data connector factory @staticmethod def get_connector(connector_identifier): return ConnectorFactory.CONNECTORS[connector_identifier]() create and instance of the required data connector :params: connector_info, information with for connection and request :type: dict | 1.654025 | 2 |
test_justify.py | anoxape/justify | 0 | 6617099 | <reponame>anoxape/justify
import pytest
from justify import justify
# Width must be greater than 0
def test_zero_width():
with pytest.raises(ValueError):
justify('', 0)
# Empty paragraph should result in an empty list
def test_empty_paragraph():
assert justify('', 1) == []
# Word longer than the width should be placed on its own line
def test_long_word():
paragraph = 'Hello, world!'
assert justify(paragraph, 1) == [
'Hello,',
'world!'
]
# Two words should be kept as one line if the width is just enough
def test_one_line():
paragraph = 'Hello, world!'
assert justify(paragraph, len(paragraph)) == [
'Hello, world!'
]
# Two words should be put on two lines if the width is not enough for both
def test_two_lines():
paragraph = 'Hello, world!'
assert justify(paragraph, len(paragraph) - 1) == [
'Hello,',
'world!'
]
# Example from the problem statement
def test_example():
paragraph = 'This is a sample text but a complicated problem to be solved, so we are adding more text to see that it actually works.'
width = 20
assert justify(paragraph, width) == [
"This is a sample",
"text but a",
"complicated problem",
"to be solved, so we",
"are adding more text",
"to see that it",
"actually works.",
]
| import pytest
from justify import justify
# Width must be greater than 0
def test_zero_width():
with pytest.raises(ValueError):
justify('', 0)
# Empty paragraph should result in an empty list
def test_empty_paragraph():
assert justify('', 1) == []
# Word longer than the width should be placed on its own line
def test_long_word():
paragraph = 'Hello, world!'
assert justify(paragraph, 1) == [
'Hello,',
'world!'
]
# Two words should be kept as one line if the width is just enough
def test_one_line():
paragraph = 'Hello, world!'
assert justify(paragraph, len(paragraph)) == [
'Hello, world!'
]
# Two words should be put on two lines if the width is not enough for both
def test_two_lines():
paragraph = 'Hello, world!'
assert justify(paragraph, len(paragraph) - 1) == [
'Hello,',
'world!'
]
# Example from the problem statement
def test_example():
paragraph = 'This is a sample text but a complicated problem to be solved, so we are adding more text to see that it actually works.'
width = 20
assert justify(paragraph, width) == [
"This is a sample",
"text but a",
"complicated problem",
"to be solved, so we",
"are adding more text",
"to see that it",
"actually works.",
] | en | 0.948397 | # Width must be greater than 0 # Empty paragraph should result in an empty list # Word longer than the width should be placed on its own line # Two words should be kept as one line if the width is just enough # Two words should be put on two lines if the width is not enough for both # Example from the problem statement | 3.68471 | 4 |
llama_trading/main.py | aagnone3/llama-trading | 1 | 6617100 | from samplealgo import algo, btest
if __name__ == '__main__':
#btest.simulate()
algo.main()
| from samplealgo import algo, btest
if __name__ == '__main__':
#btest.simulate()
algo.main()
| uk | 0.245659 | #btest.simulate() | 0.992854 | 1 |
src/media_server/admin.py | nefarius/portfolio-backend | 6 | 6617101 | from django.contrib import admin
from .models import Media
class MediaAdmin(admin.ModelAdmin):
pass
admin.site.register(Media, MediaAdmin)
| from django.contrib import admin
from .models import Media
class MediaAdmin(admin.ModelAdmin):
pass
admin.site.register(Media, MediaAdmin)
| none | 1 | 1.35009 | 1 | |
Trainning/train.py | steveho29/NCF | 0 | 6617102 | <filename>Trainning/train.py<gh_stars>0
"""
@author: <NAME>
@since: 12/21/2021 5:13 PM
@description:
@update:
"""
import json
import logging
import os
import pandas as pd
import nni
from Trainning.recommenders.utils.constants import *
import Trainning.recommenders.evaluation.python_evaluation as evaluation
from ncf_singlenode import NCF
from dataset import Dataset as NCFDataset
from Trainning.recommenders.utils.constants import SEED as DEFAULT_SEED
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("ncf")
def loadModel(dataset: NCFDataset, model_type, n_epochs=10, learning_rate=5e-3, n_factors=8, checkPoint=None):
model = NCF(
n_users=dataset.n_users,
n_items=dataset.n_items,
model_type=model_type,
n_epochs=n_epochs,
learning_rate=learning_rate,
n_factors=n_factors,
seed=DEFAULT_SEED,
)
model.setData(dataset)
if checkPoint:
if model_type == "neumf":
model.load(neumf_dir=checkPoint)
elif model_type == "gmf":
model.load(gmf_dir=checkPoint)
elif model_type == "mlp":
model.load(mlp_dir=checkPoint)
else:
raise "ModelType Invalid"
return model
def ncf_training(model: NCF, dataset: NCFDataset, checkPoint=None):
"""
Training NCF Model
"""
logger.info("Start training...")
model.fit(dataset)
if checkPoint:
model.save(checkPoint)
logger.info("Finished Training")
return model
def calculate_metrics(model, test_data, metrics_filename):
metrics_dict = {}
rating_metrics = evaluation.metrics
predictions = [
[row.userID, row.itemID, model.predict(row.userID, row.itemID)]
for (_, row) in test_data.iterrows()
]
predictions = pd.DataFrame(
predictions, columns=["userID", "itemID", "prediction"]
)
predictions = predictions.astype(
{"userID": "int64", "itemID": "int64", "prediction": "float64"}
)
print(predictions)
for metric in rating_metrics:
result = getattr(evaluation, metric)(test_data, predictions)
metrics_dict[metric] = result
# print(metrics_dict)
nni.report_final_result(metrics_dict)
# Save the metrics in a JSON file
if metrics_filename:
with open(metrics_filename, "w") as fp:
temp_dict = metrics_dict.copy()
json.dump(temp_dict, fp)
if __name__ == "__main__":
model_type = ['gmf', 'mlp', 'neumf']
for modelType in model_type:
check_point = 'model_checkpoint_' + modelType
train_data = pd.read_csv('data/ml-100k/u.data', delimiter='\t', names=DEFAULT_HEADER)
test_data = pd.read_csv('data/ml-100k/u1.test', delimiter='\t', names=DEFAULT_HEADER)
validation_data = pd.read_csv('data/ml-100k/u2.test', delimiter='\t', names=DEFAULT_HEADER)
data = NCFDataset(train=train_data, validate=validation_data, seed=DEFAULT_SEED)
# Create Model and Load the Parameters Checkpoint if exists
model = loadModel(dataset=data, model_type=modelType, n_epochs=100, learning_rate=5e-3, n_factors=8,
checkPoint=check_point)
# Training model
# Comment this line if You want evaluate model without training
ncf_training(model, dataset=data, checkPoint=check_point)
# Model Evaluation with metrics
calculate_metrics(model=model, test_data=test_data, metrics_filename='metrics_' + modelType + '.json')
| <filename>Trainning/train.py<gh_stars>0
"""
@author: <NAME>
@since: 12/21/2021 5:13 PM
@description:
@update:
"""
import json
import logging
import os
import pandas as pd
import nni
from Trainning.recommenders.utils.constants import *
import Trainning.recommenders.evaluation.python_evaluation as evaluation
from ncf_singlenode import NCF
from dataset import Dataset as NCFDataset
from Trainning.recommenders.utils.constants import SEED as DEFAULT_SEED
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("ncf")
def loadModel(dataset: NCFDataset, model_type, n_epochs=10, learning_rate=5e-3, n_factors=8, checkPoint=None):
model = NCF(
n_users=dataset.n_users,
n_items=dataset.n_items,
model_type=model_type,
n_epochs=n_epochs,
learning_rate=learning_rate,
n_factors=n_factors,
seed=DEFAULT_SEED,
)
model.setData(dataset)
if checkPoint:
if model_type == "neumf":
model.load(neumf_dir=checkPoint)
elif model_type == "gmf":
model.load(gmf_dir=checkPoint)
elif model_type == "mlp":
model.load(mlp_dir=checkPoint)
else:
raise "ModelType Invalid"
return model
def ncf_training(model: NCF, dataset: NCFDataset, checkPoint=None):
"""
Training NCF Model
"""
logger.info("Start training...")
model.fit(dataset)
if checkPoint:
model.save(checkPoint)
logger.info("Finished Training")
return model
def calculate_metrics(model, test_data, metrics_filename):
metrics_dict = {}
rating_metrics = evaluation.metrics
predictions = [
[row.userID, row.itemID, model.predict(row.userID, row.itemID)]
for (_, row) in test_data.iterrows()
]
predictions = pd.DataFrame(
predictions, columns=["userID", "itemID", "prediction"]
)
predictions = predictions.astype(
{"userID": "int64", "itemID": "int64", "prediction": "float64"}
)
print(predictions)
for metric in rating_metrics:
result = getattr(evaluation, metric)(test_data, predictions)
metrics_dict[metric] = result
# print(metrics_dict)
nni.report_final_result(metrics_dict)
# Save the metrics in a JSON file
if metrics_filename:
with open(metrics_filename, "w") as fp:
temp_dict = metrics_dict.copy()
json.dump(temp_dict, fp)
if __name__ == "__main__":
model_type = ['gmf', 'mlp', 'neumf']
for modelType in model_type:
check_point = 'model_checkpoint_' + modelType
train_data = pd.read_csv('data/ml-100k/u.data', delimiter='\t', names=DEFAULT_HEADER)
test_data = pd.read_csv('data/ml-100k/u1.test', delimiter='\t', names=DEFAULT_HEADER)
validation_data = pd.read_csv('data/ml-100k/u2.test', delimiter='\t', names=DEFAULT_HEADER)
data = NCFDataset(train=train_data, validate=validation_data, seed=DEFAULT_SEED)
# Create Model and Load the Parameters Checkpoint if exists
model = loadModel(dataset=data, model_type=modelType, n_epochs=100, learning_rate=5e-3, n_factors=8,
checkPoint=check_point)
# Training model
# Comment this line if You want evaluate model without training
ncf_training(model, dataset=data, checkPoint=check_point)
# Model Evaluation with metrics
calculate_metrics(model=model, test_data=test_data, metrics_filename='metrics_' + modelType + '.json')
| en | 0.682631 | @author: <NAME> @since: 12/21/2021 5:13 PM @description: @update: Training NCF Model # print(metrics_dict) # Save the metrics in a JSON file # Create Model and Load the Parameters Checkpoint if exists # Training model # Comment this line if You want evaluate model without training # Model Evaluation with metrics | 2.419269 | 2 |
comparisons/peregrine/peregrinearb/__init__.py | ehgp/data_606_capstone | 2 | 6617103 | """Init."""
from .async_find_opportunities import *
from .async_build_markets import *
from .bellman_multi_graph import bellman_ford_multi, NegativeWeightFinderMulti
from .bellmannx import (
bellman_ford,
calculate_profit_ratio_for_path,
NegativeWeightFinder,
NegativeWeightDepthFinder,
find_opportunities_on_exchange,
get_starting_volume,
)
from .utils import *
from .fetch_exchange_tickers import *
from .settings import *
from .multi_graph_builder import *
| """Init."""
from .async_find_opportunities import *
from .async_build_markets import *
from .bellman_multi_graph import bellman_ford_multi, NegativeWeightFinderMulti
from .bellmannx import (
bellman_ford,
calculate_profit_ratio_for_path,
NegativeWeightFinder,
NegativeWeightDepthFinder,
find_opportunities_on_exchange,
get_starting_volume,
)
from .utils import *
from .fetch_exchange_tickers import *
from .settings import *
from .multi_graph_builder import *
| none | 1 | 1.038899 | 1 | |
tests/knowledge/rules/aws/non_context_aware/encryption_enforcement_rules/encrypt_in_transit/test_ensure_cloudfront_distribution_field_level_encryption_rule.py | my-devops-info/cloudrail-knowledge | 0 | 6617104 | <filename>tests/knowledge/rules/aws/non_context_aware/encryption_enforcement_rules/encrypt_in_transit/test_ensure_cloudfront_distribution_field_level_encryption_rule.py
import unittest
from typing import List
from cloudrail.dev_tools.rule_test_utils import create_empty_entity
from cloudrail.knowledge.context.aws.cloudfront.cloud_front_distribution_list import CacheBehavior, CloudFrontDistribution
from cloudrail.knowledge.context.aws.aws_environment_context import AwsEnvironmentContext
from cloudrail.knowledge.context.terraform_action_type import TerraformActionType
from cloudrail.knowledge.context.terraform_state import TerraformState
from cloudrail.knowledge.rules.aws.non_context_aware.encryption_enforcement_rules.\
encrypt_in_transit.ensure_cloudfront_distribution_field_level_encryption_rule import EnsureCloudfrontDistributionFieldLevelEncryptionRule
from cloudrail.knowledge.rules.base_rule import RuleResultType
class TestEnsureCloudfrontDistributionFieldLevelEncryptionRule(unittest.TestCase):
def setUp(self):
self.rule = EnsureCloudfrontDistributionFieldLevelEncryptionRule()
def test_non_car_cloudfront_distribution_field_level_encryption_creating_fail(self):
# Arrange
cloudfront_dist_list: CloudFrontDistribution = create_empty_entity(CloudFrontDistribution)
cloudfront_dist_list.terraform_state = TerraformState(address='address',
action=TerraformActionType.CREATE,
resource_metadata=None,
is_new=True)
cache_behave_list: List[CacheBehavior] = [create_empty_entity(CacheBehavior), create_empty_entity(CacheBehavior)]
cache_behave_list[0].path_pattern = '*'
cache_behave_list[0].field_level_encryption_id = True
cache_behave_list[1].path_pattern = 'path'
cache_behave_list[1].precedence = 2
cloudfront_dist_list._cache_behavior_list = cache_behave_list
context = AwsEnvironmentContext(cloudfront_distribution_list=[cloudfront_dist_list])
# Act
result = self.rule.run(context, {})
# Assert
self.assertEqual(RuleResultType.FAILED, result.status)
self.assertEqual(1, len(result.issues))
def test_non_car_cloudfront_distribution_field_level_encryption_creating__no_encrypt_fail(self):
# Arrange
cloudfront_dist_list: CloudFrontDistribution = create_empty_entity(CloudFrontDistribution)
cloudfront_dist_list.terraform_state = TerraformState(address='address',
action=TerraformActionType.CREATE,
resource_metadata=None,
is_new=True)
cache_behave_list: List[CacheBehavior] = [create_empty_entity(CacheBehavior), create_empty_entity(CacheBehavior)]
cache_behave_list[0].path_pattern = '*'
cache_behave_list[0].field_level_encryption_id = False
cache_behave_list[1].path_pattern = 'path'
cache_behave_list[1].precedence = 2
cache_behave_list[1].field_level_encryption_id = False
cloudfront_dist_list._cache_behavior_list = cache_behave_list
context = AwsEnvironmentContext(cloudfront_distribution_list=[cloudfront_dist_list])
# Act
result = self.rule.run(context, {})
# Assert
self.assertEqual(RuleResultType.FAILED, result.status)
self.assertEqual(1, len(result.issues))
def test_non_car_cloudfront_distribution_field_level_encryption_creating__ordered_list_fail(self):
# Arrange
cloudfront_dist_list: CloudFrontDistribution = create_empty_entity(CloudFrontDistribution)
cloudfront_dist_list.terraform_state = TerraformState(address='address',
action=TerraformActionType.CREATE,
resource_metadata=None,
is_new=True)
cache_behave_list: List[CacheBehavior] = [create_empty_entity(CacheBehavior), create_empty_entity(CacheBehavior)]
cache_behave_list[0].path_pattern = '*'
cache_behave_list[0].field_level_encryption_id = False
cache_behave_list[1].path_pattern = 'path'
cache_behave_list[1].precedence = 2
cloudfront_dist_list._cache_behavior_list = cache_behave_list
context = AwsEnvironmentContext(cloudfront_distribution_list=[cloudfront_dist_list])
# Act
result = self.rule.run(context, {})
# Assert
self.assertEqual(RuleResultType.FAILED, result.status)
self.assertEqual(1, len(result.issues))
def test_non_car_cloudfront_distribution_field_level_encryption_creating__not_new__pass(self):
# Arrange
cloudfront_dist_list: CloudFrontDistribution = create_empty_entity(CloudFrontDistribution)
cloudfront_dist_list.terraform_state = TerraformState(address='address',
action=TerraformActionType.CREATE,
resource_metadata=None,
is_new=False)
cache_behave_list: List[CacheBehavior] = [create_empty_entity(CacheBehavior), create_empty_entity(CacheBehavior)]
cache_behave_list[0].path_pattern = '*'
cache_behave_list[0].field_level_encryption_id = False
cache_behave_list[1].path_pattern = 'path'
cache_behave_list[1].precedence = 2
cloudfront_dist_list._cache_behavior_list = cache_behave_list
context = AwsEnvironmentContext(cloudfront_distribution_list=[cloudfront_dist_list])
# Act
result = self.rule.run(context, {})
# Assert
self.assertEqual(RuleResultType.SUCCESS, result.status)
self.assertEqual(0, len(result.issues))
def test_non_car_cloudfront_distribution_field_level_encryption_creating_pass(self):
# Arrange
cloudfront_dist_list: CloudFrontDistribution = create_empty_entity(CloudFrontDistribution)
cloudfront_dist_list.terraform_state = TerraformState(address='address',
action=TerraformActionType.CREATE,
resource_metadata=None,
is_new=True)
cache_behave_list: List[CacheBehavior] = [create_empty_entity(CacheBehavior), create_empty_entity(CacheBehavior)]
cache_behave_list[0].path_pattern = '*'
cache_behave_list[0].field_level_encryption_id = True
cache_behave_list[1].path_pattern = 'path'
cache_behave_list[1].precedence = 2
cache_behave_list[1].field_level_encryption_id = True
cloudfront_dist_list._cache_behavior_list = cache_behave_list
context = AwsEnvironmentContext(cloudfront_distribution_list=[cloudfront_dist_list])
# Act
result = self.rule.run(context, {})
# Assert
self.assertEqual(RuleResultType.SUCCESS, result.status)
self.assertEqual(0, len(result.issues))
| <filename>tests/knowledge/rules/aws/non_context_aware/encryption_enforcement_rules/encrypt_in_transit/test_ensure_cloudfront_distribution_field_level_encryption_rule.py
import unittest
from typing import List
from cloudrail.dev_tools.rule_test_utils import create_empty_entity
from cloudrail.knowledge.context.aws.cloudfront.cloud_front_distribution_list import CacheBehavior, CloudFrontDistribution
from cloudrail.knowledge.context.aws.aws_environment_context import AwsEnvironmentContext
from cloudrail.knowledge.context.terraform_action_type import TerraformActionType
from cloudrail.knowledge.context.terraform_state import TerraformState
from cloudrail.knowledge.rules.aws.non_context_aware.encryption_enforcement_rules.\
encrypt_in_transit.ensure_cloudfront_distribution_field_level_encryption_rule import EnsureCloudfrontDistributionFieldLevelEncryptionRule
from cloudrail.knowledge.rules.base_rule import RuleResultType
class TestEnsureCloudfrontDistributionFieldLevelEncryptionRule(unittest.TestCase):
def setUp(self):
self.rule = EnsureCloudfrontDistributionFieldLevelEncryptionRule()
def test_non_car_cloudfront_distribution_field_level_encryption_creating_fail(self):
# Arrange
cloudfront_dist_list: CloudFrontDistribution = create_empty_entity(CloudFrontDistribution)
cloudfront_dist_list.terraform_state = TerraformState(address='address',
action=TerraformActionType.CREATE,
resource_metadata=None,
is_new=True)
cache_behave_list: List[CacheBehavior] = [create_empty_entity(CacheBehavior), create_empty_entity(CacheBehavior)]
cache_behave_list[0].path_pattern = '*'
cache_behave_list[0].field_level_encryption_id = True
cache_behave_list[1].path_pattern = 'path'
cache_behave_list[1].precedence = 2
cloudfront_dist_list._cache_behavior_list = cache_behave_list
context = AwsEnvironmentContext(cloudfront_distribution_list=[cloudfront_dist_list])
# Act
result = self.rule.run(context, {})
# Assert
self.assertEqual(RuleResultType.FAILED, result.status)
self.assertEqual(1, len(result.issues))
def test_non_car_cloudfront_distribution_field_level_encryption_creating__no_encrypt_fail(self):
# Arrange
cloudfront_dist_list: CloudFrontDistribution = create_empty_entity(CloudFrontDistribution)
cloudfront_dist_list.terraform_state = TerraformState(address='address',
action=TerraformActionType.CREATE,
resource_metadata=None,
is_new=True)
cache_behave_list: List[CacheBehavior] = [create_empty_entity(CacheBehavior), create_empty_entity(CacheBehavior)]
cache_behave_list[0].path_pattern = '*'
cache_behave_list[0].field_level_encryption_id = False
cache_behave_list[1].path_pattern = 'path'
cache_behave_list[1].precedence = 2
cache_behave_list[1].field_level_encryption_id = False
cloudfront_dist_list._cache_behavior_list = cache_behave_list
context = AwsEnvironmentContext(cloudfront_distribution_list=[cloudfront_dist_list])
# Act
result = self.rule.run(context, {})
# Assert
self.assertEqual(RuleResultType.FAILED, result.status)
self.assertEqual(1, len(result.issues))
def test_non_car_cloudfront_distribution_field_level_encryption_creating__ordered_list_fail(self):
# Arrange
cloudfront_dist_list: CloudFrontDistribution = create_empty_entity(CloudFrontDistribution)
cloudfront_dist_list.terraform_state = TerraformState(address='address',
action=TerraformActionType.CREATE,
resource_metadata=None,
is_new=True)
cache_behave_list: List[CacheBehavior] = [create_empty_entity(CacheBehavior), create_empty_entity(CacheBehavior)]
cache_behave_list[0].path_pattern = '*'
cache_behave_list[0].field_level_encryption_id = False
cache_behave_list[1].path_pattern = 'path'
cache_behave_list[1].precedence = 2
cloudfront_dist_list._cache_behavior_list = cache_behave_list
context = AwsEnvironmentContext(cloudfront_distribution_list=[cloudfront_dist_list])
# Act
result = self.rule.run(context, {})
# Assert
self.assertEqual(RuleResultType.FAILED, result.status)
self.assertEqual(1, len(result.issues))
def test_non_car_cloudfront_distribution_field_level_encryption_creating__not_new__pass(self):
# Arrange
cloudfront_dist_list: CloudFrontDistribution = create_empty_entity(CloudFrontDistribution)
cloudfront_dist_list.terraform_state = TerraformState(address='address',
action=TerraformActionType.CREATE,
resource_metadata=None,
is_new=False)
cache_behave_list: List[CacheBehavior] = [create_empty_entity(CacheBehavior), create_empty_entity(CacheBehavior)]
cache_behave_list[0].path_pattern = '*'
cache_behave_list[0].field_level_encryption_id = False
cache_behave_list[1].path_pattern = 'path'
cache_behave_list[1].precedence = 2
cloudfront_dist_list._cache_behavior_list = cache_behave_list
context = AwsEnvironmentContext(cloudfront_distribution_list=[cloudfront_dist_list])
# Act
result = self.rule.run(context, {})
# Assert
self.assertEqual(RuleResultType.SUCCESS, result.status)
self.assertEqual(0, len(result.issues))
def test_non_car_cloudfront_distribution_field_level_encryption_creating_pass(self):
# Arrange
cloudfront_dist_list: CloudFrontDistribution = create_empty_entity(CloudFrontDistribution)
cloudfront_dist_list.terraform_state = TerraformState(address='address',
action=TerraformActionType.CREATE,
resource_metadata=None,
is_new=True)
cache_behave_list: List[CacheBehavior] = [create_empty_entity(CacheBehavior), create_empty_entity(CacheBehavior)]
cache_behave_list[0].path_pattern = '*'
cache_behave_list[0].field_level_encryption_id = True
cache_behave_list[1].path_pattern = 'path'
cache_behave_list[1].precedence = 2
cache_behave_list[1].field_level_encryption_id = True
cloudfront_dist_list._cache_behavior_list = cache_behave_list
context = AwsEnvironmentContext(cloudfront_distribution_list=[cloudfront_dist_list])
# Act
result = self.rule.run(context, {})
# Assert
self.assertEqual(RuleResultType.SUCCESS, result.status)
self.assertEqual(0, len(result.issues))
| en | 0.85204 | # Arrange # Act # Assert # Arrange # Act # Assert # Arrange # Act # Assert # Arrange # Act # Assert # Arrange # Act # Assert | 1.903036 | 2 |
wasch/serializers.py | waschag-tvk/pywaschedv | 1 | 6617105 | from rest_framework import serializers
from .models import Appointment
class AppointmentSerializer(serializers.ModelSerializer):
class Meta:
model = Appointment
fields = ('pk', 'time', 'machine', 'reference')
| from rest_framework import serializers
from .models import Appointment
class AppointmentSerializer(serializers.ModelSerializer):
class Meta:
model = Appointment
fields = ('pk', 'time', 'machine', 'reference')
| none | 1 | 2.084266 | 2 | |
Collatz_conjecture.py | cdigap/Python_Scripts | 0 | 6617106 | <filename>Collatz_conjecture.py
# <NAME> 2018-02-06
# Collatz_conjecture: https://en.wikipedia.org/wiki/Collatz_conjecture
# User Input requested - no validations yet
m = int(input("Enter a Number : "))
n = m
while n >= 1:
if n == 1:
exit()
elif n % 2 == 0:
n = n / 2
print(n)
else:
n = (n * 3) + 1
print(n)
| <filename>Collatz_conjecture.py
# <NAME> 2018-02-06
# Collatz_conjecture: https://en.wikipedia.org/wiki/Collatz_conjecture
# User Input requested - no validations yet
m = int(input("Enter a Number : "))
n = m
while n >= 1:
if n == 1:
exit()
elif n % 2 == 0:
n = n / 2
print(n)
else:
n = (n * 3) + 1
print(n)
| en | 0.432014 | # <NAME> 2018-02-06 # Collatz_conjecture: https://en.wikipedia.org/wiki/Collatz_conjecture # User Input requested - no validations yet | 3.914862 | 4 |
data_collection/ner_handler/ner_training/DenemeTrain-NER.py | fourplusone41/AcikHack2-GazetedenTariheBakis | 15 | 6617107 | <filename>data_collection/ner_handler/ner_training/DenemeTrain-NER.py
# coding: utf-8
# In[3]:
from jpype import JClass, JString, getDefaultJVMPath, shutdownJVM, startJVM
# In[5]:
startJVM(
getDefaultJVMPath(),
'-ea',
'-Djava.class.path=zemberek-full.jar',
convertStrings=False
)
# In[6]:
Paths: JClass = JClass('java.nio.file.Paths')
# In[39]:
trainPath = Paths.get("./enamex_train.txt")
testPath = Paths.get("./enamex_test.txt")
modelRoot = Paths.get("./enamex_model")
# In[42]:
NerDataSet: JClass=JClass('zemberek.ner.NerDataSet')
AnnotationStyle: JClass=JClass('zemberek.ner.NerDataSet.AnnotationStyle')
TurkishMorphology: JClass=JClass('zemberek.morphology.TurkishMorphology')
PerceptronNerTrainer: JClass=JClass('zemberek.ner.PerceptronNerTrainer')
# In[43]:
trainingSet = NerDataSet.load(trainPath, AnnotationStyle.ENAMEX);
# In[44]:
trainingSet.info()
# In[45]:
testSet = NerDataSet.load(testPath, AnnotationStyle.ENAMEX);
# In[46]:
testSet.info()
# In[47]:
morphology = TurkishMorphology.createWithDefaults();
# In[48]:
morphology.toString()
# In[49]:
ner = PerceptronNerTrainer(morphology).train(trainingSet, testSet, 7, 0.1);
# In[50]:
ner.saveModelAsText(modelRoot);
| <filename>data_collection/ner_handler/ner_training/DenemeTrain-NER.py
# coding: utf-8
# In[3]:
from jpype import JClass, JString, getDefaultJVMPath, shutdownJVM, startJVM
# In[5]:
startJVM(
getDefaultJVMPath(),
'-ea',
'-Djava.class.path=zemberek-full.jar',
convertStrings=False
)
# In[6]:
Paths: JClass = JClass('java.nio.file.Paths')
# In[39]:
trainPath = Paths.get("./enamex_train.txt")
testPath = Paths.get("./enamex_test.txt")
modelRoot = Paths.get("./enamex_model")
# In[42]:
NerDataSet: JClass=JClass('zemberek.ner.NerDataSet')
AnnotationStyle: JClass=JClass('zemberek.ner.NerDataSet.AnnotationStyle')
TurkishMorphology: JClass=JClass('zemberek.morphology.TurkishMorphology')
PerceptronNerTrainer: JClass=JClass('zemberek.ner.PerceptronNerTrainer')
# In[43]:
trainingSet = NerDataSet.load(trainPath, AnnotationStyle.ENAMEX);
# In[44]:
trainingSet.info()
# In[45]:
testSet = NerDataSet.load(testPath, AnnotationStyle.ENAMEX);
# In[46]:
testSet.info()
# In[47]:
morphology = TurkishMorphology.createWithDefaults();
# In[48]:
morphology.toString()
# In[49]:
ner = PerceptronNerTrainer(morphology).train(trainingSet, testSet, 7, 0.1);
# In[50]:
ner.saveModelAsText(modelRoot);
| en | 0.175657 | # coding: utf-8 # In[3]: # In[5]: # In[6]: # In[39]: # In[42]: # In[43]: # In[44]: # In[45]: # In[46]: # In[47]: # In[48]: # In[49]: # In[50]: | 2.067162 | 2 |
Operations/harmonicdifference.py | InnovAnon-Inc/sceadar | 0 | 6617108 | <filename>Operations/harmonicdifference.py
from Util.util import Util
from Operations.operations import Operations
class HarmonicDifference (Operations):
@staticmethod
def sop (value1, value2): return 2.0 / (1.0 / value1 + 1.0 / value2)
def __init__ (self,
min_value1, max_value1,
min_value2, max_value2):
if 0 in xrange (min_value1, max_value1 + 1): raise Exception (
"0 in [%s, %s]" % (min_value1, max_value1))
if 0 in xrange (min_value2, max_value2 + 1): raise Exception (
"0 in [%s, %s]" % (min_value2, max_value2))
min_value = HarmonicDifference.sop (min_value1, min_value2)
max_value = HarmonicDifference.sop (max_value1, max_value2)
Operations.__init__ (self, min_value, max_value,
(min_value1, max_value1),
(min_value2, max_value2))
def op (self, value1, value2):
Operations.op (self, value1, value2)
ret = HarmonicDifference.sop (value1, value2)
self.validateOp (ret)
return ret | <filename>Operations/harmonicdifference.py
from Util.util import Util
from Operations.operations import Operations
class HarmonicDifference (Operations):
@staticmethod
def sop (value1, value2): return 2.0 / (1.0 / value1 + 1.0 / value2)
def __init__ (self,
min_value1, max_value1,
min_value2, max_value2):
if 0 in xrange (min_value1, max_value1 + 1): raise Exception (
"0 in [%s, %s]" % (min_value1, max_value1))
if 0 in xrange (min_value2, max_value2 + 1): raise Exception (
"0 in [%s, %s]" % (min_value2, max_value2))
min_value = HarmonicDifference.sop (min_value1, min_value2)
max_value = HarmonicDifference.sop (max_value1, max_value2)
Operations.__init__ (self, min_value, max_value,
(min_value1, max_value1),
(min_value2, max_value2))
def op (self, value1, value2):
Operations.op (self, value1, value2)
ret = HarmonicDifference.sop (value1, value2)
self.validateOp (ret)
return ret | none | 1 | 3.118883 | 3 | |
bom/utils.py | FixturFab/django-bomf | 0 | 6617109 | <filename>bom/utils.py
# This file is to have no project dependencies
def increment_char(c):
"""
Increment an uppercase character, returning 'A' if 'Z' is given
"""
return chr(ord(c) + 1) if c != 'Z' else 'A'
def increment_str(s):
lpart = s.rstrip('Z')
num_replacements = len(s) - len(lpart)
new_s = lpart[:-1] + increment_char(lpart[-1]) if lpart else 'A'
new_s += 'A' * num_replacements
return new_s
# The following function is based upon code from <NAME>, see:
#
# https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/
#
# Code has been adapted for for use as sort function for Python sorted(). Enables sorting an
# iterable whose items are strings represented by a mix of alphanumeric characters. For the
# default sort for {'R14', 'R5'} is:
#
# R14 R5
#
# but with prep_for_sorting_nicely the sort will be what is more naturally expected:
#
# R5 R14
#
import re
def prep_for_sorting_nicely(item):
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return alphanum_key(item)
# Convert a string with delimited fields into a list of fields. Delimiters are comma,
# semi-colon, colon, tab, or blank space. Fields may contain any printable character.
def listify_string(st):
ss = re.split(' |:|;|,|\t|\n', st)
split_st = []
for s in ss:
s_strip = s.strip()
if len(s_strip) != 0:
split_st.append(s_strip)
return split_st
# Convert a list of items into a comma-separated string without any surrounding brackets,
# for example:
#
# list = [1, 2, 3 4]
#
# becomes '1, 2, 3, 4'
#
# as compared to str(list) which
#
# becomes '[1, 2, 3 4]'
def stringify_list(li):
return ', '.join(str(x) for x in li)
# Check a string reference designator for duplicates as compared to a running set of
# reference already seen. A reference designator may contain multiple delimited references,
# so need to check the new designator for duplicates before checking against references
# already seen. All duplicate references are added to the set duplicate_refs.
def check_references_for_duplicates(new_refs, seen_refs, duplicate_refs):
new_refs_list = listify_string(new_refs)
new_refs_set = set()
for r in new_refs_list:
if r in new_refs_set:
duplicate_refs.add(r)
else:
new_refs_set.add(r)
if r in seen_refs:
duplicate_refs.add(r)
seen_refs.add(r)
# Given a string that represents a number, returns a string that eliminates trailing zeros
# and decimal point if any from the input. For example, 25.000 become 25. If the input
# string that does not represent a number then the original string is returned.
def strip_trailing_zeros(num):
found = False
for c in num:
if c.isdigit():
found = True
elif c not in ['-', '+', '.']:
found = False
break
return ('%f' % float(num)).rstrip('0').rstrip('.') if found else num
# Input a dict with a list of key options, return the value if it exists, else None
def get_from_dict(input_dict, key_options):
for key in key_options:
val = input_dict.get(key, None)
if val:
return val
return None | <filename>bom/utils.py
# This file is to have no project dependencies
def increment_char(c):
"""
Increment an uppercase character, returning 'A' if 'Z' is given
"""
return chr(ord(c) + 1) if c != 'Z' else 'A'
def increment_str(s):
lpart = s.rstrip('Z')
num_replacements = len(s) - len(lpart)
new_s = lpart[:-1] + increment_char(lpart[-1]) if lpart else 'A'
new_s += 'A' * num_replacements
return new_s
# The following function is based upon code from <NAME>, see:
#
# https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/
#
# Code has been adapted for for use as sort function for Python sorted(). Enables sorting an
# iterable whose items are strings represented by a mix of alphanumeric characters. For the
# default sort for {'R14', 'R5'} is:
#
# R14 R5
#
# but with prep_for_sorting_nicely the sort will be what is more naturally expected:
#
# R5 R14
#
import re
def prep_for_sorting_nicely(item):
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return alphanum_key(item)
# Convert a string with delimited fields into a list of fields. Delimiters are comma,
# semi-colon, colon, tab, or blank space. Fields may contain any printable character.
def listify_string(st):
ss = re.split(' |:|;|,|\t|\n', st)
split_st = []
for s in ss:
s_strip = s.strip()
if len(s_strip) != 0:
split_st.append(s_strip)
return split_st
# Convert a list of items into a comma-separated string without any surrounding brackets,
# for example:
#
# list = [1, 2, 3 4]
#
# becomes '1, 2, 3, 4'
#
# as compared to str(list) which
#
# becomes '[1, 2, 3 4]'
def stringify_list(li):
return ', '.join(str(x) for x in li)
# Check a string reference designator for duplicates as compared to a running set of
# reference already seen. A reference designator may contain multiple delimited references,
# so need to check the new designator for duplicates before checking against references
# already seen. All duplicate references are added to the set duplicate_refs.
def check_references_for_duplicates(new_refs, seen_refs, duplicate_refs):
new_refs_list = listify_string(new_refs)
new_refs_set = set()
for r in new_refs_list:
if r in new_refs_set:
duplicate_refs.add(r)
else:
new_refs_set.add(r)
if r in seen_refs:
duplicate_refs.add(r)
seen_refs.add(r)
# Given a string that represents a number, returns a string that eliminates trailing zeros
# and decimal point if any from the input. For example, 25.000 become 25. If the input
# string that does not represent a number then the original string is returned.
def strip_trailing_zeros(num):
found = False
for c in num:
if c.isdigit():
found = True
elif c not in ['-', '+', '.']:
found = False
break
return ('%f' % float(num)).rstrip('0').rstrip('.') if found else num
# Input a dict with a list of key options, return the value if it exists, else None
def get_from_dict(input_dict, key_options):
for key in key_options:
val = input_dict.get(key, None)
if val:
return val
return None | en | 0.823621 | # This file is to have no project dependencies Increment an uppercase character, returning 'A' if 'Z' is given # The following function is based upon code from <NAME>, see: # # https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ # # Code has been adapted for for use as sort function for Python sorted(). Enables sorting an # iterable whose items are strings represented by a mix of alphanumeric characters. For the # default sort for {'R14', 'R5'} is: # # R14 R5 # # but with prep_for_sorting_nicely the sort will be what is more naturally expected: # # R5 R14 # # Convert a string with delimited fields into a list of fields. Delimiters are comma, # semi-colon, colon, tab, or blank space. Fields may contain any printable character. # Convert a list of items into a comma-separated string without any surrounding brackets, # for example: # # list = [1, 2, 3 4] # # becomes '1, 2, 3, 4' # # as compared to str(list) which # # becomes '[1, 2, 3 4]' # Check a string reference designator for duplicates as compared to a running set of # reference already seen. A reference designator may contain multiple delimited references, # so need to check the new designator for duplicates before checking against references # already seen. All duplicate references are added to the set duplicate_refs. # Given a string that represents a number, returns a string that eliminates trailing zeros # and decimal point if any from the input. For example, 25.000 become 25. If the input # string that does not represent a number then the original string is returned. # Input a dict with a list of key options, return the value if it exists, else None | 3.384873 | 3 |
utils.py | poya-kob/BiaBegard | 0 | 6617110 | import os
import string
import random
import datetime
def get_file_name(filepath):
size = 8
chars = string.ascii_uppercase + string.digits
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
name = ''.join(random.choice(chars) for _ in range(size))
return name, ext
def upload_image_path(instance, filename):
date = datetime.datetime.now()
name, ext = get_file_name(filename)
new_name = f"{name}{ext}"
if type(instance).__name__ == "Products":
return f"product/{date.year}/{date.month}/{date.day}/{new_name}"
elif type(instance).__name__ == "ProductsGalleries":
return f"Products_Galleries/{date.year}/{date.month}/{date.day}/{new_name}"
elif type(instance).__name__ == "Brands":
return f"Brands/{date.year}/{date.month}/{date.day}/{new_name}"
elif type(instance).__name__ == "Slider":
return f"Slider/{date.year}/{date.month}/{date.day}/{new_name}"
elif type(instance).__name__ == "Blog":
return f"Blog/{date.year}/{date.month}/{date.day}/{new_name}"
elif type(instance).__name__ == "SiteSetting":
return f"SiteSetting/{date.year}/{date.month}/{date.day}/{new_name}"
| import os
import string
import random
import datetime
def get_file_name(filepath):
size = 8
chars = string.ascii_uppercase + string.digits
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
name = ''.join(random.choice(chars) for _ in range(size))
return name, ext
def upload_image_path(instance, filename):
date = datetime.datetime.now()
name, ext = get_file_name(filename)
new_name = f"{name}{ext}"
if type(instance).__name__ == "Products":
return f"product/{date.year}/{date.month}/{date.day}/{new_name}"
elif type(instance).__name__ == "ProductsGalleries":
return f"Products_Galleries/{date.year}/{date.month}/{date.day}/{new_name}"
elif type(instance).__name__ == "Brands":
return f"Brands/{date.year}/{date.month}/{date.day}/{new_name}"
elif type(instance).__name__ == "Slider":
return f"Slider/{date.year}/{date.month}/{date.day}/{new_name}"
elif type(instance).__name__ == "Blog":
return f"Blog/{date.year}/{date.month}/{date.day}/{new_name}"
elif type(instance).__name__ == "SiteSetting":
return f"SiteSetting/{date.year}/{date.month}/{date.day}/{new_name}"
| none | 1 | 2.949343 | 3 | |
Sudoku Solver.py | jdlauret/SudokuSolver | 0 | 6617111 | <filename>Sudoku Solver.py
assignments = []
rows = 'ABCDEFGHI'
cols = '123456789'
def cross(a, b):
# returns box notation for grid ie. A1, B1, A2, B2
return [s+t for s in a for t in b]
# contains all boxes for grid
boxes = cross(rows, cols)
# contains all rows in grid
row_units = [cross(r, cols) for r in rows]
# contains all columns in grid
col_units = [cross(rows, c) for c in cols]
# contains all squares in grid
square_units = [cross(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')]
# contains first diagonal
diagonal1 = [a[0]+a[1] for a in zip(rows, cols)]
# contains second diagonal
diagonal2 = [a[0]+a[1] for a in zip(rows, cols[::-1])]
# contains both diagonal
diagonal_units = [diagonal1, diagonal2]
def assign_value(values, box, value):
# Assigns a value to a given box. If it updates the board record it.
if values[box] == value:
return values
values[box] = value
if len(value) == 1:
assignments.append(values.copy())
return values
def grid_values(grid):
# converts a string containing the board layout into a dictionary
grid_dict = {}
values = '123456789'
for i, char in enumerate(grid):
if char == '.':
grid_dict[boxes[i]] = values
else:
grid_dict[boxes[i]] = char
return grid_dict
def display(values):
# prints a representation of the sudoku board based on the values contained within in the dictionary
width = 1+max(len(values[s]) for s in boxes)
line = '+'.join(['-'*(width*3)]*3)
for r in rows:
print(''.join(values[r+c].center(width)+('|' if c in '36' else '') for c in cols))
if r in 'CF':
print(line)
return
def naked_twins(values):
# naked_twins searches for naked twins and removes values from the relevant peers
# finds twin candidates
solved_values = [box for box in values.keys() if len(values[box]) == 1]
twin_candidates = []
for box in boxes:
if len(values[box]) == 2:
if box not in twin_candidates:
twin_candidates.append(box)
# finds if any of the candidates are peers of each other
pairs = []
for candidate in twin_candidates:
for i in range(0, len(twin_candidates)):
if candidate != twin_candidates[i]:
if twin_candidates[i] in peers[candidate]:
if values[twin_candidates[i]] == values[candidate]:
if sorted([twin_candidates[i], candidate]) not in pairs:
pairs.append(sorted([twin_candidates[i], candidate]))
# finds all peers of a twins and removes the values found in the twin from the peers
for pair in pairs:
box_1 = pair[0]
box_2 = pair[1]
for unit in unit_list:
if box_1 in unit\
and box_2 in unit:
for box in unit:
if box not in solved_values\
and box not in pair:
for digit in values[box_1]:
new_value = values[box].replace(digit, '')
assign_value(values, box, new_value)
# returns the adjusted values
return values
def eliminate(values):
# eliminate finds solved boxes and removes the solved value from all of it's peers
solved_values = [box for box in values.keys() if len(values[box]) == 1]
for box in solved_values:
value = values[box]
for peer in peers[box]:
new_value = values[peer].replace(value, '')
assign_value(values, peer, new_value)
return values
def only_choice(values):
# only_choice searches for if there is only one box in a unit which would allow a certain value,
# then that box is assigned that value
for unit in unit_list:
for digit in '123456789':
digits_found = []
for cell in unit:
if digit in values[cell]:
digits_found.append(cell)
if len(digits_found) == 1:
assign_value(values, digits_found[0], digit)
return values
def reduce_puzzle(values):
# reduce_puzzle runs a set of values through eliminate(), only_choice(), and naked_twins()
# until the values before and after are the same
# if the values are the same it exits the loop and returns the values
# if any values are completely removed resulting in a length of 0
# the function returns a False
stalled = False
while not stalled:
if isinstance(values, str):
values = grid_values(values)
solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])
values = only_choice(
naked_twins(
eliminate(values)
)
)
solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])
stalled = solved_values_before == solved_values_after
if len([box for box in values.keys() if len(values[box]) == 0]):
return False
return values
def search(values):
# uses reduce_puzzle
# creates a search tree by finding the box with the minimum number of possible options
# creates a copy for each possible options contained in the box
# attempts to solve each of the possible options recursively with the left most option first
values = reduce_puzzle(values)
if values is False:
return False
if all(len(values[s]) == 1 for s in boxes):
return values
num, box = min(
# creates list of tuples and searches for the min value in the list
(len(values[box]), box)
for box in boxes if len(values[box]) > 1
)
for value in values[box]:
new_sudoku = values.copy()
new_sudoku[box] = value
attempt = search(new_sudoku)
if attempt:
return attempt
def solve(grid):
# used string input and coverts it to a grid
# then hands off the grid to search to be solved
values = grid_values(grid)
return search(values)
if __name__ == '__main__':
"""
HOW TO USE:
Find any sudoku puzzle you want to solve
A good place to look is http://sudoku.menu/
If you select a puzzle where the diagonals can be solved make sure to change solve_diagonals to True
"""
solve_diagonals = False
# Example Puzzles
diagonal_sudoku = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
very_hard_sudoku = '.46.1......28.....1.32.......872.4...9.....2...7.613.......71.2.....58......9.73.'
if solve_diagonals:
# list with all units
unit_list = row_units + col_units + square_units + diagonal_units
else:
unit_list = row_units + col_units + square_units
units = dict((s, [u for u in unit_list if s in u]) for s in boxes)
peers = dict((s, set(sum(units[s], [])) - set([s])) for s in boxes)
# contains the grid in a string format
# displays solved grid
# visualizes the solving of the grid
display(solve(very_hard_sudoku))
| <filename>Sudoku Solver.py
assignments = []
rows = 'ABCDEFGHI'
cols = '123456789'
def cross(a, b):
# returns box notation for grid ie. A1, B1, A2, B2
return [s+t for s in a for t in b]
# contains all boxes for grid
boxes = cross(rows, cols)
# contains all rows in grid
row_units = [cross(r, cols) for r in rows]
# contains all columns in grid
col_units = [cross(rows, c) for c in cols]
# contains all squares in grid
square_units = [cross(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')]
# contains first diagonal
diagonal1 = [a[0]+a[1] for a in zip(rows, cols)]
# contains second diagonal
diagonal2 = [a[0]+a[1] for a in zip(rows, cols[::-1])]
# contains both diagonal
diagonal_units = [diagonal1, diagonal2]
def assign_value(values, box, value):
# Assigns a value to a given box. If it updates the board record it.
if values[box] == value:
return values
values[box] = value
if len(value) == 1:
assignments.append(values.copy())
return values
def grid_values(grid):
# converts a string containing the board layout into a dictionary
grid_dict = {}
values = '123456789'
for i, char in enumerate(grid):
if char == '.':
grid_dict[boxes[i]] = values
else:
grid_dict[boxes[i]] = char
return grid_dict
def display(values):
# prints a representation of the sudoku board based on the values contained within in the dictionary
width = 1+max(len(values[s]) for s in boxes)
line = '+'.join(['-'*(width*3)]*3)
for r in rows:
print(''.join(values[r+c].center(width)+('|' if c in '36' else '') for c in cols))
if r in 'CF':
print(line)
return
def naked_twins(values):
# naked_twins searches for naked twins and removes values from the relevant peers
# finds twin candidates
solved_values = [box for box in values.keys() if len(values[box]) == 1]
twin_candidates = []
for box in boxes:
if len(values[box]) == 2:
if box not in twin_candidates:
twin_candidates.append(box)
# finds if any of the candidates are peers of each other
pairs = []
for candidate in twin_candidates:
for i in range(0, len(twin_candidates)):
if candidate != twin_candidates[i]:
if twin_candidates[i] in peers[candidate]:
if values[twin_candidates[i]] == values[candidate]:
if sorted([twin_candidates[i], candidate]) not in pairs:
pairs.append(sorted([twin_candidates[i], candidate]))
# finds all peers of a twins and removes the values found in the twin from the peers
for pair in pairs:
box_1 = pair[0]
box_2 = pair[1]
for unit in unit_list:
if box_1 in unit\
and box_2 in unit:
for box in unit:
if box not in solved_values\
and box not in pair:
for digit in values[box_1]:
new_value = values[box].replace(digit, '')
assign_value(values, box, new_value)
# returns the adjusted values
return values
def eliminate(values):
# eliminate finds solved boxes and removes the solved value from all of it's peers
solved_values = [box for box in values.keys() if len(values[box]) == 1]
for box in solved_values:
value = values[box]
for peer in peers[box]:
new_value = values[peer].replace(value, '')
assign_value(values, peer, new_value)
return values
def only_choice(values):
# only_choice searches for if there is only one box in a unit which would allow a certain value,
# then that box is assigned that value
for unit in unit_list:
for digit in '123456789':
digits_found = []
for cell in unit:
if digit in values[cell]:
digits_found.append(cell)
if len(digits_found) == 1:
assign_value(values, digits_found[0], digit)
return values
def reduce_puzzle(values):
# reduce_puzzle runs a set of values through eliminate(), only_choice(), and naked_twins()
# until the values before and after are the same
# if the values are the same it exits the loop and returns the values
# if any values are completely removed resulting in a length of 0
# the function returns a False
stalled = False
while not stalled:
if isinstance(values, str):
values = grid_values(values)
solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])
values = only_choice(
naked_twins(
eliminate(values)
)
)
solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])
stalled = solved_values_before == solved_values_after
if len([box for box in values.keys() if len(values[box]) == 0]):
return False
return values
def search(values):
# uses reduce_puzzle
# creates a search tree by finding the box with the minimum number of possible options
# creates a copy for each possible options contained in the box
# attempts to solve each of the possible options recursively with the left most option first
values = reduce_puzzle(values)
if values is False:
return False
if all(len(values[s]) == 1 for s in boxes):
return values
num, box = min(
# creates list of tuples and searches for the min value in the list
(len(values[box]), box)
for box in boxes if len(values[box]) > 1
)
for value in values[box]:
new_sudoku = values.copy()
new_sudoku[box] = value
attempt = search(new_sudoku)
if attempt:
return attempt
def solve(grid):
# used string input and coverts it to a grid
# then hands off the grid to search to be solved
values = grid_values(grid)
return search(values)
if __name__ == '__main__':
"""
HOW TO USE:
Find any sudoku puzzle you want to solve
A good place to look is http://sudoku.menu/
If you select a puzzle where the diagonals can be solved make sure to change solve_diagonals to True
"""
solve_diagonals = False
# Example Puzzles
diagonal_sudoku = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
very_hard_sudoku = '.46.1......28.....1.32.......872.4...9.....2...7.613.......71.2.....58......9.73.'
if solve_diagonals:
# list with all units
unit_list = row_units + col_units + square_units + diagonal_units
else:
unit_list = row_units + col_units + square_units
units = dict((s, [u for u in unit_list if s in u]) for s in boxes)
peers = dict((s, set(sum(units[s], [])) - set([s])) for s in boxes)
# contains the grid in a string format
# displays solved grid
# visualizes the solving of the grid
display(solve(very_hard_sudoku))
| en | 0.835949 | # returns box notation for grid ie. A1, B1, A2, B2 # contains all boxes for grid # contains all rows in grid # contains all columns in grid # contains all squares in grid # contains first diagonal # contains second diagonal # contains both diagonal # Assigns a value to a given box. If it updates the board record it. # converts a string containing the board layout into a dictionary # prints a representation of the sudoku board based on the values contained within in the dictionary # naked_twins searches for naked twins and removes values from the relevant peers # finds twin candidates # finds if any of the candidates are peers of each other # finds all peers of a twins and removes the values found in the twin from the peers # returns the adjusted values # eliminate finds solved boxes and removes the solved value from all of it's peers # only_choice searches for if there is only one box in a unit which would allow a certain value, # then that box is assigned that value # reduce_puzzle runs a set of values through eliminate(), only_choice(), and naked_twins() # until the values before and after are the same # if the values are the same it exits the loop and returns the values # if any values are completely removed resulting in a length of 0 # the function returns a False # uses reduce_puzzle # creates a search tree by finding the box with the minimum number of possible options # creates a copy for each possible options contained in the box # attempts to solve each of the possible options recursively with the left most option first # creates list of tuples and searches for the min value in the list # used string input and coverts it to a grid # then hands off the grid to search to be solved HOW TO USE: Find any sudoku puzzle you want to solve A good place to look is http://sudoku.menu/ If you select a puzzle where the diagonals can be solved make sure to change solve_diagonals to True # Example Puzzles # list with all units # contains the grid in a string format # displays solved grid # visualizes the solving of the grid | 3.797735 | 4 |
phat/metrics.py | ZuckermanLab/phat | 0 | 6617112 | """Distance functions on path space."""
from scipy.spatial.distance import directed_hausdorff
def symmetric_difference_cardinality(s, q):
"""Return the cardinality of the symmetric difference of two sets.
Parameters
----------
s : iterable
Elements of the first set. Values must be hashable.
q : iterable
Elements of the second set. Values must be hashable.
Returns
-------
int
``len(set(s) ^ set(q))``.
"""
return len(set(s) ^ set(q))
def hausdorff(s, q):
return max(directed_hausdorff(s, q), directed_hausdorff(q, s))
| """Distance functions on path space."""
from scipy.spatial.distance import directed_hausdorff
def symmetric_difference_cardinality(s, q):
"""Return the cardinality of the symmetric difference of two sets.
Parameters
----------
s : iterable
Elements of the first set. Values must be hashable.
q : iterable
Elements of the second set. Values must be hashable.
Returns
-------
int
``len(set(s) ^ set(q))``.
"""
return len(set(s) ^ set(q))
def hausdorff(s, q):
return max(directed_hausdorff(s, q), directed_hausdorff(q, s))
| en | 0.534604 | Distance functions on path space. Return the cardinality of the symmetric difference of two sets. Parameters ---------- s : iterable Elements of the first set. Values must be hashable. q : iterable Elements of the second set. Values must be hashable. Returns ------- int ``len(set(s) ^ set(q))``. | 3.640806 | 4 |
wifi.py | alrobyii/wifi-password | 0 | 6617113 | <gh_stars>0
from tkinter import *
import pyperclip
root = Tk()
root.geometry("900x900")
pass_details = StringVar()
myList = []
def wifi_pass():
import subprocess
global myList
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\n')
profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]
myList.append("------------------------")
for i in profiles:
results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear']).decode('utf-8').split('\n')
results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
try:
myList.append(" Wifi-->" + i)
# myList.append("--")
myList.append(" /Password-->" +results[0])
myList.append(" -//- ")
except IndexError:
myList.append(" Wifi-->" +i)
# myList.append("--")
myList.append(" ")
def show_wifi():
def listToString(s):
# initialize an empty string
myStr = ""
# traverse in the string
for ele in s:
myStr = myStr + ele + "\n"
# return string
return myStr
myStr = listToString(myList)
pass_details.set(myStr)
def copytoclipboard():
password = <PASSWORD>()
pyperclip.copy(password)
Label(root, text="Gui Wifi Password Checker", font="calibri 20 bold").place(x = 60,y = 50)
Button(root, text="Initiate Process Now", command=wifi_pass).place(x = 60, y = 90)
Button(root, text="Show wifi Passwords", command=show_wifi).place(x = 60, y = 130)
Entry(root, textvariable=pass_details).place(width=800, height=50, x = 60, y = 160)
Button(root, text="Copy to clipbord", command=copytoclipboard).place(x = 60, y = 220)
root.mainloop()
| from tkinter import *
import pyperclip
root = Tk()
root.geometry("900x900")
pass_details = StringVar()
myList = []
def wifi_pass():
import subprocess
global myList
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\n')
profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]
myList.append("------------------------")
for i in profiles:
results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear']).decode('utf-8').split('\n')
results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
try:
myList.append(" Wifi-->" + i)
# myList.append("--")
myList.append(" /Password-->" +results[0])
myList.append(" -//- ")
except IndexError:
myList.append(" Wifi-->" +i)
# myList.append("--")
myList.append(" ")
def show_wifi():
def listToString(s):
# initialize an empty string
myStr = ""
# traverse in the string
for ele in s:
myStr = myStr + ele + "\n"
# return string
return myStr
myStr = listToString(myList)
pass_details.set(myStr)
def copytoclipboard():
password = <PASSWORD>()
pyperclip.copy(password)
Label(root, text="Gui Wifi Password Checker", font="calibri 20 bold").place(x = 60,y = 50)
Button(root, text="Initiate Process Now", command=wifi_pass).place(x = 60, y = 90)
Button(root, text="Show wifi Passwords", command=show_wifi).place(x = 60, y = 130)
Entry(root, textvariable=pass_details).place(width=800, height=50, x = 60, y = 160)
Button(root, text="Copy to clipbord", command=copytoclipboard).place(x = 60, y = 220)
root.mainloop() | en | 0.074665 | # myList.append("--") # myList.append("--") # initialize an empty string # traverse in the string # return string | 3.095855 | 3 |
api2/helpers.py | shyam-patel-kira/LA-CO-SS | 0 | 6617114 | import pickle;
def save(variable, flieName):
with open(flieName, 'wb') as f:
pickle.dump(variable, f);
def load(flieName):
with open(flieName, 'rb') as f:
b = pickle.load(f)
return b;
| import pickle;
def save(variable, flieName):
with open(flieName, 'wb') as f:
pickle.dump(variable, f);
def load(flieName):
with open(flieName, 'rb') as f:
b = pickle.load(f)
return b;
| none | 1 | 3.077417 | 3 | |
main.py | EmadGKamel/IoThings | 5 | 6617115 | import sys
import time
from os import path
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import paho.mqtt.subscribe as subscribe
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUiType
FORM_CLASS, _ = loadUiType(path.join(path.dirname(__file__), "IoThings.ui"))
class MainApp(QMainWindow, FORM_CLASS):
def __init__(self, parent=None):
super(MainApp, self).__init__(parent)
QMainWindow.__init__(self)
self.setupUi(self)
self.init_ui()
self.handle_buttons()
def init_ui(self):
self.setFixedSize(450, 600)
self.setWindowTitle('IoThings')
self.setWindowIcon(QIcon("iot.png"))
def handle_buttons(self):
self.connect.clicked.connect(self.handle_connect)
self.pub.clicked.connect(self.handle_publish)
self.sub.clicked.connect(self.handle_subscrib)
def handle_connect(self):
hostname = str(self.host.text())
port = int(self.port.text())
mqtt_client = mqtt.Client(client_id="0", clean_session=True, userdata=None, transport="tcp")
mqtt_client.connect(hostname, port=port, keepalive=60)
def handle_publish(self):
publish_topic = str(self.pubtop.text())
publish_message = str(self.pubmsg.toPlainText())
publish.single(publish_topic, publish_message)
def handle_subscrib(self):
subscribe_topic = str(self.subtop.text())
subscribe_message = subscribe.simple(subscribe_topic)
self.submsg.setPlainText(subscribe_message.payload)
def main():
app = QApplication(sys.argv)
window = MainApp()
window.show()
app.exec_()
if __name__ == '__main__':
main() | import sys
import time
from os import path
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import paho.mqtt.subscribe as subscribe
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUiType
FORM_CLASS, _ = loadUiType(path.join(path.dirname(__file__), "IoThings.ui"))
class MainApp(QMainWindow, FORM_CLASS):
def __init__(self, parent=None):
super(MainApp, self).__init__(parent)
QMainWindow.__init__(self)
self.setupUi(self)
self.init_ui()
self.handle_buttons()
def init_ui(self):
self.setFixedSize(450, 600)
self.setWindowTitle('IoThings')
self.setWindowIcon(QIcon("iot.png"))
def handle_buttons(self):
self.connect.clicked.connect(self.handle_connect)
self.pub.clicked.connect(self.handle_publish)
self.sub.clicked.connect(self.handle_subscrib)
def handle_connect(self):
hostname = str(self.host.text())
port = int(self.port.text())
mqtt_client = mqtt.Client(client_id="0", clean_session=True, userdata=None, transport="tcp")
mqtt_client.connect(hostname, port=port, keepalive=60)
def handle_publish(self):
publish_topic = str(self.pubtop.text())
publish_message = str(self.pubmsg.toPlainText())
publish.single(publish_topic, publish_message)
def handle_subscrib(self):
subscribe_topic = str(self.subtop.text())
subscribe_message = subscribe.simple(subscribe_topic)
self.submsg.setPlainText(subscribe_message.payload)
def main():
app = QApplication(sys.argv)
window = MainApp()
window.show()
app.exec_()
if __name__ == '__main__':
main() | none | 1 | 2.552445 | 3 | |
compass/tests/test_models.py | osule/bookworm | 0 | 6617116 | <reponame>osule/bookworm
from django.test import TestCase
from compass.models import (Category,
Book, Compass)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestCase):
def test_can_add_book(self):
category = Category.create(title="Mock Category")
Book.create(title="Mock Book", category=category)
self.assertEqual(Book.find("Mock Book").count(), 1)
class CompassTestCase(TestCase):
def test_correct_title_if_title_and_category(self,):
heading = Compass.heading(title="Title 1", category="Category 1")
self.assertEqual(heading, "All books like Title 1 under Category 1")
def test_correct_title_if_not_title_and_category(self,):
heading = Compass.heading(title="", category="")
self.assertEqual(heading, "All books")
def test_correct_title_if_not_category(self,):
heading = Compass.heading(title="Title 1", category="")
self.assertEqual(heading, "All book titles like Title 1")
def test_correct_title_if_not_title(self,):
heading = Compass.heading(title="", category="Category 1")
self.assertEqual(heading, "All book titles under Category 1")
| from django.test import TestCase
from compass.models import (Category,
Book, Compass)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestCase):
def test_can_add_book(self):
category = Category.create(title="Mock Category")
Book.create(title="Mock Book", category=category)
self.assertEqual(Book.find("Mock Book").count(), 1)
class CompassTestCase(TestCase):
def test_correct_title_if_title_and_category(self,):
heading = Compass.heading(title="Title 1", category="Category 1")
self.assertEqual(heading, "All books like Title 1 under Category 1")
def test_correct_title_if_not_title_and_category(self,):
heading = Compass.heading(title="", category="")
self.assertEqual(heading, "All books")
def test_correct_title_if_not_category(self,):
heading = Compass.heading(title="Title 1", category="")
self.assertEqual(heading, "All book titles like Title 1")
def test_correct_title_if_not_title(self,):
heading = Compass.heading(title="", category="Category 1")
self.assertEqual(heading, "All book titles under Category 1") | none | 1 | 2.794288 | 3 | |
mstat.py | ToxicFrog/mo | 0 | 6617117 | <filename>mstat.py
#!/usr/bin/python2
from __future__ import print_function
import re
import sys
import os
from mutagen.id3 import ID3NoHeaderError
from mutagen.easyid3 import EasyID3
from music import findMusic
from args import parser, subparsers
def utf8(str):
if isinstance(str, unicode):
return str
return unicode(str, 'utf-8')
subparser = parser.add_subcommand('stat', help='display file information',
description="""
Display tags for one or many files.
""")
subparser.add_argument('paths', type=utf8, nargs='*', default=[u"."], help='paths to search for music files in, default "."')
def main(options):
music = findMusic(options.paths)
for i,tags in enumerate(music):
print("[%d/%d] %s" % (i, len(music), tags.file))
print("", type(tags))
for k,v in enumerate(tags._tags):
print("", k, v, tags[v])
print("")
subparser.set_defaults(func=main, command='stat')
if __name__ == "__main__":
main(parser.parse_args())
| <filename>mstat.py
#!/usr/bin/python2
from __future__ import print_function
import re
import sys
import os
from mutagen.id3 import ID3NoHeaderError
from mutagen.easyid3 import EasyID3
from music import findMusic
from args import parser, subparsers
def utf8(str):
if isinstance(str, unicode):
return str
return unicode(str, 'utf-8')
subparser = parser.add_subcommand('stat', help='display file information',
description="""
Display tags for one or many files.
""")
subparser.add_argument('paths', type=utf8, nargs='*', default=[u"."], help='paths to search for music files in, default "."')
def main(options):
music = findMusic(options.paths)
for i,tags in enumerate(music):
print("[%d/%d] %s" % (i, len(music), tags.file))
print("", type(tags))
for k,v in enumerate(tags._tags):
print("", k, v, tags[v])
print("")
subparser.set_defaults(func=main, command='stat')
if __name__ == "__main__":
main(parser.parse_args())
| en | 0.446122 | #!/usr/bin/python2 Display tags for one or many files. | 2.579534 | 3 |
bot.py | SyneroDev/Paint | 0 | 6617118 | import discord
import cogs
from templatebot import Bot
from discord import AllowedMentions, Activity, Game
from os import environ as env
from dotenv import load_dotenv
bot = Bot(
name="Paint",
command_prefix="p!",
allowed_mentions=AllowedMentions(
everyone=False, roles=False, users=True),
activity=Game("with colors!"),
)
bot.VERSION = "1.0.0"
for i in cogs.default:
bot.load_extension(f"cogs.{i}")
bot.run(env.get("TOKEN", None)) | import discord
import cogs
from templatebot import Bot
from discord import AllowedMentions, Activity, Game
from os import environ as env
from dotenv import load_dotenv
bot = Bot(
name="Paint",
command_prefix="p!",
allowed_mentions=AllowedMentions(
everyone=False, roles=False, users=True),
activity=Game("with colors!"),
)
bot.VERSION = "1.0.0"
for i in cogs.default:
bot.load_extension(f"cogs.{i}")
bot.run(env.get("TOKEN", None)) | none | 1 | 2.083466 | 2 | |
src/RPi_Python/Lights+Temp+Motion.py | Dharun-Anand/IoTSmartHub | 0 | 6617119 | #Author: <NAME>
#Date: 7/25/20
import RPi.GPIO as GPIO #import the RPi.GPIO module to use the board GPIO pins
import pyrebase #import the pyrebase module to communicate with the firebase
import time #import the time modulde to add delays
import Adafruit_DHT #import DHT sensor libraries
config = { #define dictionary named config with several key-value pairs that configure the connection to the firebase database
"apiKey": "<KEY>",
"authDomain": "iothomesystem1.firebaseapp.com",
"databaseURL": "https://iothomesystem1.firebaseio.com/",
"storageBucket": "iothomesystem1.appspot.com"
}
firebase = pyrebase.initialize_app(config) #initialize communication with the firebase database
#GPIO Setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#Lights Setup
lights = 17 #set GPIO pin 17 for lights
GPIO.setup(lights, GPIO.OUT)
#Temp & Humidity Sensory Setup
THsensor = Adafruit_DHT.DHT11
THpin = 27 #set GPIO pin 27 for TH sensor
#Motion Detector Setup
pir = 22
GPIO.setup(pir, GPIO.IN) #setup GPIO pin 22 for motion
def initialize():
GPIO.output(lights, True)
database = firebase.database() #take an instance from the firebase database
database.child("IoTHomeSystem1").child("System").set("OFF") #set all keys to off for initialization
database.child("IoTHomeSystem1").child("Lights").set("OFF") # ...
database.child("IoTHomeSystem1").child("TH").child("Temp").set("0.00")
database.child("IoTHomeSystem1").child("TH").child("Humid").set("0.00")
database.child("IoTHomeSystem1").child("Motion").set("OFF")
def lightFunc():
database = firebase.database()
lightStatus = database.child("IoTHomeSystem1").child("Lights").get().val() #get status of lights
if "off" in lightStatus.lower(): #if value is off, turn LED off
GPIO.output(lights, True)
else: #if value is on, turn LED on
GPIO.output(lights, False)
def THFunc():
database = firebase.database()
humidity, temperature = Adafruit_DHT.read_retry(THsensor, THpin) #get reading from TH sensor
if humidity is not None and temperature is not None:
str_temp = ' {0:0.2f}'.format(temperature)
str_humid = ' {0:0.2f}'.format(humidity)
database.child("IoTHomeSystem1").child("TH").child("Temp").set(str_temp) #send readings to firebase database
database.child("IoTHomeSystem1").child("TH").child("Humid").set(str_humid) # ...
def pirFunc():
if GPIO.input(pir) == True: #if motion pin goes high, motion is detected
database.child("IoTHomeSystem1").child("Motion").set("ON")
else:
database.child("IoTHomeSystem1").child("Motion").set("OFF")
try:
initialize()
database = firebase.database()
while(True):
sysStatus = database.child("IoTHomeSystem1").child("System").get().val() #get status of system
if "on" in sysStatus.lower(): #if system on, monitor all components
lightFunc()
THFunc()
pirFunc()
if "off" in sysStatus.lower(): #if system off, set all components to off
initialize()
time.sleep(0.1)
except KeyboardInterrupt: #if CTRL+C is pressed, exit cleanly:
initialize()
GPIO.cleanup() #cleanup all GPIO
| #Author: <NAME>
#Date: 7/25/20
import RPi.GPIO as GPIO #import the RPi.GPIO module to use the board GPIO pins
import pyrebase #import the pyrebase module to communicate with the firebase
import time #import the time modulde to add delays
import Adafruit_DHT #import DHT sensor libraries
config = { #define dictionary named config with several key-value pairs that configure the connection to the firebase database
"apiKey": "<KEY>",
"authDomain": "iothomesystem1.firebaseapp.com",
"databaseURL": "https://iothomesystem1.firebaseio.com/",
"storageBucket": "iothomesystem1.appspot.com"
}
firebase = pyrebase.initialize_app(config) #initialize communication with the firebase database
#GPIO Setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#Lights Setup
lights = 17 #set GPIO pin 17 for lights
GPIO.setup(lights, GPIO.OUT)
#Temp & Humidity Sensory Setup
THsensor = Adafruit_DHT.DHT11
THpin = 27 #set GPIO pin 27 for TH sensor
#Motion Detector Setup
pir = 22
GPIO.setup(pir, GPIO.IN) #setup GPIO pin 22 for motion
def initialize():
GPIO.output(lights, True)
database = firebase.database() #take an instance from the firebase database
database.child("IoTHomeSystem1").child("System").set("OFF") #set all keys to off for initialization
database.child("IoTHomeSystem1").child("Lights").set("OFF") # ...
database.child("IoTHomeSystem1").child("TH").child("Temp").set("0.00")
database.child("IoTHomeSystem1").child("TH").child("Humid").set("0.00")
database.child("IoTHomeSystem1").child("Motion").set("OFF")
def lightFunc():
database = firebase.database()
lightStatus = database.child("IoTHomeSystem1").child("Lights").get().val() #get status of lights
if "off" in lightStatus.lower(): #if value is off, turn LED off
GPIO.output(lights, True)
else: #if value is on, turn LED on
GPIO.output(lights, False)
def THFunc():
database = firebase.database()
humidity, temperature = Adafruit_DHT.read_retry(THsensor, THpin) #get reading from TH sensor
if humidity is not None and temperature is not None:
str_temp = ' {0:0.2f}'.format(temperature)
str_humid = ' {0:0.2f}'.format(humidity)
database.child("IoTHomeSystem1").child("TH").child("Temp").set(str_temp) #send readings to firebase database
database.child("IoTHomeSystem1").child("TH").child("Humid").set(str_humid) # ...
def pirFunc():
if GPIO.input(pir) == True: #if motion pin goes high, motion is detected
database.child("IoTHomeSystem1").child("Motion").set("ON")
else:
database.child("IoTHomeSystem1").child("Motion").set("OFF")
try:
initialize()
database = firebase.database()
while(True):
sysStatus = database.child("IoTHomeSystem1").child("System").get().val() #get status of system
if "on" in sysStatus.lower(): #if system on, monitor all components
lightFunc()
THFunc()
pirFunc()
if "off" in sysStatus.lower(): #if system off, set all components to off
initialize()
time.sleep(0.1)
except KeyboardInterrupt: #if CTRL+C is pressed, exit cleanly:
initialize()
GPIO.cleanup() #cleanup all GPIO
| en | 0.725242 | #Author: <NAME> #Date: 7/25/20 #import the RPi.GPIO module to use the board GPIO pins #import the pyrebase module to communicate with the firebase #import the time modulde to add delays #import DHT sensor libraries #define dictionary named config with several key-value pairs that configure the connection to the firebase database #initialize communication with the firebase database #GPIO Setup #Lights Setup #set GPIO pin 17 for lights #Temp & Humidity Sensory Setup #set GPIO pin 27 for TH sensor #Motion Detector Setup #setup GPIO pin 22 for motion #take an instance from the firebase database #set all keys to off for initialization # ... #get status of lights #if value is off, turn LED off #if value is on, turn LED on #get reading from TH sensor #send readings to firebase database # ... #if motion pin goes high, motion is detected #get status of system #if system on, monitor all components #if system off, set all components to off #if CTRL+C is pressed, exit cleanly: #cleanup all GPIO | 2.782055 | 3 |
p2python/__init__.py | JonathanVusich/p2python | 0 | 6617120 | <filename>p2python/__init__.py
__name__ = ["p2python"]
__author__ = "<NAME> <EMAIL>"
| <filename>p2python/__init__.py
__name__ = ["p2python"]
__author__ = "<NAME> <EMAIL>"
| none | 1 | 1.208496 | 1 | |
autumn/models/covid_19/detection.py | jtrauer/AuTuMN | 0 | 6617121 | <filename>autumn/models/covid_19/detection.py<gh_stars>0
from typing import Callable, Optional, Tuple, Any, List
import numpy as np
from summer.compute import ComputedValueProcessor
from autumn.tools.inputs.covid_btn.queries import get_btn_testing_numbers
from autumn.tools.inputs.testing.eur_testing_data import (
get_uk_testing_numbers,
get_eu_testing_numbers,
)
from autumn.tools.inputs.covid_au.queries import get_vic_testing_numbers
from autumn.tools.inputs.covid_phl.queries import get_phl_subregion_testing_numbers
from autumn.tools.inputs.covid_lka.queries import get_lka_testing_numbers
from autumn.tools.inputs.covid_mmr.queries import get_mmr_testing_numbers
from autumn.tools.inputs.covid_bgd.queries import get_coxs_bazar_testing_numbers
from autumn.tools.inputs.owid.queries import get_international_testing_numbers
from autumn.tools.inputs import get_population_by_agegroup
from autumn.tools.utils.utils import apply_moving_average
from autumn.tools.curve import scale_up_function
from autumn.models.covid_19.stratifications.agegroup import AGEGROUP_STRATA
class CdrProc(ComputedValueProcessor):
"""
Calculate prevalence from the active disease compartments.
"""
def __init__(self, detected_proportion_func):
self.detected_proportion_func = detected_proportion_func
def process(self, compartment_values, computed_values, time):
"""
Calculate the actual prevalence during run-time.
"""
return self.detected_proportion_func(time)
def get_testing_numbers_for_region(
country_iso3: str, subregion: Optional[str]
) -> Tuple[list, list]:
"""
Use the appropriate function to retrieve the testing numbers applicable to the region being modelled.
Functions are taken from the autumn input tools module, as above.
"""
subregion = subregion or False
if country_iso3 == "AUS":
test_dates, test_values = get_vic_testing_numbers()
elif country_iso3 == "PHL":
phl_region = subregion.lower() if subregion else "philippines"
test_dates, test_values = get_phl_subregion_testing_numbers(phl_region)
elif subregion == "Sabah":
test_dates, test_values = get_international_testing_numbers(country_iso3)
elif country_iso3 == "GBR":
test_dates, test_values = get_uk_testing_numbers()
elif country_iso3 in {"BEL", "ITA", "SWE", "FRA", "ESP"}:
test_dates, test_values = get_eu_testing_numbers(country_iso3)
elif country_iso3 == "LKA":
test_dates, test_values = get_lka_testing_numbers()
elif country_iso3 == "MMR":
test_dates, test_values = get_mmr_testing_numbers()
elif country_iso3 == "BGD" and subregion == "FDMN":
test_dates, test_values = get_coxs_bazar_testing_numbers()
elif country_iso3 == "BTN":
test_dates, test_values = get_btn_testing_numbers(subregion)
else:
test_dates, test_values = get_international_testing_numbers(country_iso3)
assert len(test_dates) == len(
test_values
), "Length of test dates and test values are not equal"
return test_dates, test_values
def create_cdr_function(assumed_tests: int, assumed_cdr: float) -> Callable:
"""
Factory function for finding CDRs from number of tests done in setting modelled
To work out the function, only one parameter is needed, so this can be estimated from one known point on the curve,
being a value of the CDR that is associated with a certain testing rate
:param assumed_cdr: float
Value of CDR associated with the testing coverage
:param assumed_tests: int
Number of tests needed to result in this CDR
:return: callable
Function to provide CDR for a certain number of tests
"""
# Find the single unknown parameter to the function - i.e. for minus b, where CDR = 1 - exp(-b * t)
exponent_multiplier = np.log(1.0 - assumed_cdr) / assumed_tests
# Construct the function based on this parameter
def cdr_function(tests_per_capita):
return 1.0 - np.exp(exponent_multiplier * tests_per_capita)
return cdr_function
def inflate_test_data(
test_multiplier: float, test_dates: list, test_values: list
) -> List[float]:
"""
Apply inflation factor to test numbers if requested.
Used in the Philippines applications only.
"""
# Add future test datapoints to original series so we can scale-up
latest_per_capita_tests = test_values[-1]
for time, value in zip(test_multiplier.times, test_multiplier.values):
if time not in test_dates:
test_dates = np.append(test_dates, [time])
test_values.append(latest_per_capita_tests)
# Reorder the data
sorted_pairs = sorted(zip(test_dates, test_values))
tuples = zip(*sorted_pairs)
test_dates, test_values = [list(tup) for tup in tuples]
# Create scale-up function
testing_scale_up = scale_up_function(
test_multiplier.times, test_multiplier.values, method=4
)
# Scale up added tests
return [
test_values[val] * testing_scale_up(time) for val, time in enumerate(test_dates)
]
def find_cdr_function_from_test_data(
test_detect_params, iso3: str, region: str, year: int
) -> Callable:
"""
Sort out case detection rate from testing numbers, sequentially calling the functions above as required.
"""
# Get the testing population denominator
testing_pops = get_population_by_agegroup(AGEGROUP_STRATA, iso3, region, year=year)
# Get the numbers of tests performed
test_dates, test_values = get_testing_numbers_for_region(iso3, region)
# Convert test numbers to per capita testing rates
per_capita_tests = [i_tests / sum(testing_pops) for i_tests in test_values]
# Smooth the testing data if requested
if test_detect_params.smoothing_period:
smoothed_per_capita_tests = apply_moving_average(
per_capita_tests, test_detect_params.smoothing_period
)
else:
smoothed_per_capita_tests = per_capita_tests
# Scale testing with a time-variant request parameter
if test_detect_params.test_multiplier:
smoothed_inflated_per_capita_tests = inflate_test_data(
test_detect_params.test_multiplier, test_dates, smoothed_per_capita_tests
)
else:
smoothed_inflated_per_capita_tests = smoothed_per_capita_tests
assert all((val >= 0.0 for val in smoothed_inflated_per_capita_tests))
# Calculate CDRs and the resulting CDR function
cdr_from_tests_func: Callable[[Any], float] = create_cdr_function(
test_detect_params.assumed_tests_parameter,
test_detect_params.assumed_cdr_parameter,
)
# Get the final CDR function
cdr_function = scale_up_function(
test_dates,
[
cdr_from_tests_func(i_test_rate)
for i_test_rate in smoothed_inflated_per_capita_tests
],
smoothness=0.2,
method=4,
bound_low=0.0,
)
return cdr_function
| <filename>autumn/models/covid_19/detection.py<gh_stars>0
from typing import Callable, Optional, Tuple, Any, List
import numpy as np
from summer.compute import ComputedValueProcessor
from autumn.tools.inputs.covid_btn.queries import get_btn_testing_numbers
from autumn.tools.inputs.testing.eur_testing_data import (
get_uk_testing_numbers,
get_eu_testing_numbers,
)
from autumn.tools.inputs.covid_au.queries import get_vic_testing_numbers
from autumn.tools.inputs.covid_phl.queries import get_phl_subregion_testing_numbers
from autumn.tools.inputs.covid_lka.queries import get_lka_testing_numbers
from autumn.tools.inputs.covid_mmr.queries import get_mmr_testing_numbers
from autumn.tools.inputs.covid_bgd.queries import get_coxs_bazar_testing_numbers
from autumn.tools.inputs.owid.queries import get_international_testing_numbers
from autumn.tools.inputs import get_population_by_agegroup
from autumn.tools.utils.utils import apply_moving_average
from autumn.tools.curve import scale_up_function
from autumn.models.covid_19.stratifications.agegroup import AGEGROUP_STRATA
class CdrProc(ComputedValueProcessor):
"""
Calculate prevalence from the active disease compartments.
"""
def __init__(self, detected_proportion_func):
self.detected_proportion_func = detected_proportion_func
def process(self, compartment_values, computed_values, time):
"""
Calculate the actual prevalence during run-time.
"""
return self.detected_proportion_func(time)
def get_testing_numbers_for_region(
country_iso3: str, subregion: Optional[str]
) -> Tuple[list, list]:
"""
Use the appropriate function to retrieve the testing numbers applicable to the region being modelled.
Functions are taken from the autumn input tools module, as above.
"""
subregion = subregion or False
if country_iso3 == "AUS":
test_dates, test_values = get_vic_testing_numbers()
elif country_iso3 == "PHL":
phl_region = subregion.lower() if subregion else "philippines"
test_dates, test_values = get_phl_subregion_testing_numbers(phl_region)
elif subregion == "Sabah":
test_dates, test_values = get_international_testing_numbers(country_iso3)
elif country_iso3 == "GBR":
test_dates, test_values = get_uk_testing_numbers()
elif country_iso3 in {"BEL", "ITA", "SWE", "FRA", "ESP"}:
test_dates, test_values = get_eu_testing_numbers(country_iso3)
elif country_iso3 == "LKA":
test_dates, test_values = get_lka_testing_numbers()
elif country_iso3 == "MMR":
test_dates, test_values = get_mmr_testing_numbers()
elif country_iso3 == "BGD" and subregion == "FDMN":
test_dates, test_values = get_coxs_bazar_testing_numbers()
elif country_iso3 == "BTN":
test_dates, test_values = get_btn_testing_numbers(subregion)
else:
test_dates, test_values = get_international_testing_numbers(country_iso3)
assert len(test_dates) == len(
test_values
), "Length of test dates and test values are not equal"
return test_dates, test_values
def create_cdr_function(assumed_tests: int, assumed_cdr: float) -> Callable:
"""
Factory function for finding CDRs from number of tests done in setting modelled
To work out the function, only one parameter is needed, so this can be estimated from one known point on the curve,
being a value of the CDR that is associated with a certain testing rate
:param assumed_cdr: float
Value of CDR associated with the testing coverage
:param assumed_tests: int
Number of tests needed to result in this CDR
:return: callable
Function to provide CDR for a certain number of tests
"""
# Find the single unknown parameter to the function - i.e. for minus b, where CDR = 1 - exp(-b * t)
exponent_multiplier = np.log(1.0 - assumed_cdr) / assumed_tests
# Construct the function based on this parameter
def cdr_function(tests_per_capita):
return 1.0 - np.exp(exponent_multiplier * tests_per_capita)
return cdr_function
def inflate_test_data(
test_multiplier: float, test_dates: list, test_values: list
) -> List[float]:
"""
Apply inflation factor to test numbers if requested.
Used in the Philippines applications only.
"""
# Add future test datapoints to original series so we can scale-up
latest_per_capita_tests = test_values[-1]
for time, value in zip(test_multiplier.times, test_multiplier.values):
if time not in test_dates:
test_dates = np.append(test_dates, [time])
test_values.append(latest_per_capita_tests)
# Reorder the data
sorted_pairs = sorted(zip(test_dates, test_values))
tuples = zip(*sorted_pairs)
test_dates, test_values = [list(tup) for tup in tuples]
# Create scale-up function
testing_scale_up = scale_up_function(
test_multiplier.times, test_multiplier.values, method=4
)
# Scale up added tests
return [
test_values[val] * testing_scale_up(time) for val, time in enumerate(test_dates)
]
def find_cdr_function_from_test_data(
test_detect_params, iso3: str, region: str, year: int
) -> Callable:
"""
Sort out case detection rate from testing numbers, sequentially calling the functions above as required.
"""
# Get the testing population denominator
testing_pops = get_population_by_agegroup(AGEGROUP_STRATA, iso3, region, year=year)
# Get the numbers of tests performed
test_dates, test_values = get_testing_numbers_for_region(iso3, region)
# Convert test numbers to per capita testing rates
per_capita_tests = [i_tests / sum(testing_pops) for i_tests in test_values]
# Smooth the testing data if requested
if test_detect_params.smoothing_period:
smoothed_per_capita_tests = apply_moving_average(
per_capita_tests, test_detect_params.smoothing_period
)
else:
smoothed_per_capita_tests = per_capita_tests
# Scale testing with a time-variant request parameter
if test_detect_params.test_multiplier:
smoothed_inflated_per_capita_tests = inflate_test_data(
test_detect_params.test_multiplier, test_dates, smoothed_per_capita_tests
)
else:
smoothed_inflated_per_capita_tests = smoothed_per_capita_tests
assert all((val >= 0.0 for val in smoothed_inflated_per_capita_tests))
# Calculate CDRs and the resulting CDR function
cdr_from_tests_func: Callable[[Any], float] = create_cdr_function(
test_detect_params.assumed_tests_parameter,
test_detect_params.assumed_cdr_parameter,
)
# Get the final CDR function
cdr_function = scale_up_function(
test_dates,
[
cdr_from_tests_func(i_test_rate)
for i_test_rate in smoothed_inflated_per_capita_tests
],
smoothness=0.2,
method=4,
bound_low=0.0,
)
return cdr_function
| en | 0.815632 | Calculate prevalence from the active disease compartments. Calculate the actual prevalence during run-time. Use the appropriate function to retrieve the testing numbers applicable to the region being modelled. Functions are taken from the autumn input tools module, as above. Factory function for finding CDRs from number of tests done in setting modelled To work out the function, only one parameter is needed, so this can be estimated from one known point on the curve, being a value of the CDR that is associated with a certain testing rate :param assumed_cdr: float Value of CDR associated with the testing coverage :param assumed_tests: int Number of tests needed to result in this CDR :return: callable Function to provide CDR for a certain number of tests # Find the single unknown parameter to the function - i.e. for minus b, where CDR = 1 - exp(-b * t) # Construct the function based on this parameter Apply inflation factor to test numbers if requested. Used in the Philippines applications only. # Add future test datapoints to original series so we can scale-up # Reorder the data # Create scale-up function # Scale up added tests Sort out case detection rate from testing numbers, sequentially calling the functions above as required. # Get the testing population denominator # Get the numbers of tests performed # Convert test numbers to per capita testing rates # Smooth the testing data if requested # Scale testing with a time-variant request parameter # Calculate CDRs and the resulting CDR function # Get the final CDR function | 2.266215 | 2 |
scripts/map_and_ped.py | chengsoonong/opengwas | 5 | 6617122 | #!/usr/bin/python
import sn
import sys,string
import numpy as np
import math
import csv
import os.path
from collections import namedtuple
import os
import vcf
import fnmatch
from optparse import OptionParser
import time
class MapAndPed:
"""
This classe allow create and parse .map and .ped files to be used in PLINK.
"""
def __init__(self, outputmap, outputped,outputmap_parse=None, outputped_parse=None):
"""
Initialaze the output names of the files and other variables
"""
#self.outputmap = "Phobia-test5.map"
#self.outputped = "Phobia-test5.ped"
self.outputmap = outputmap
self.outputped = outputped
self.outputmap_parse = outputmap_parse
self.outputped_parse = outputped_parse
self.idx_rem=[]
self.all_rs=[]
self.valid_alleles = ['AA', 'AT', 'AG', 'AC',
'CA', 'CT', 'CG', 'CC',
'TA', 'TT', 'TG', 'TC',
'GA', 'GT', 'GG', 'GC']
self.Family_ID=1
self.Individual_ID=1
self.chrommosomos=np.array(["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","X","Y","MT"])
def create_map(self, folders_case, folders_control):
"""Create the .map file"""
print "\n\nMAP FILE (",time.asctime(),")\n"
dir_list=folders_case[:]
dir_list.extend(folders_control)
files=[]
file_dir={}
map_list=[]
idx=0
for i in dir_list:
files.extend(os.listdir(i)) #it get all files names in a dir
for j in os.listdir(i):
file_dir[j]=i #dictionari with file:dir
print "Reading the files:\n\n",file_dir[files[0]]+"/"+files[0], #parse the first file
try:
snps = sn.parse(file_dir[files[0]]+"/"+files[0])#take the first file
for i in snps: #initialaze rs_list and map_list with the first file
map_list.append((i[0],i[2],i[3]))
except:
print " ERRO 1"
print ""
dtype = [('rs', 'S10'), ('chrom', 'S10'), ('position', int)]
map_list = np.array( map_list, dtype=dtype)
for j in files[1:]:
map_list_tmp=[]
print file_dir[j]+"/"+j,
try:
snps = sn.parse(file_dir[j]+"/"+j) #take another files
except:
print " ERRO 2"
continue
try:
for i in snps:
map_list_tmp.append((i[0],i[2],i[3]))
except:
print " ERRO 3"
continue
print ""
map_list_tmp=np.array(map_list_tmp, dtype=dtype)
map_list=np.array(np.concatenate(( map_list, map_list_tmp)) , dtype=dtype)
u, indices = np.unique( map_list['rs'] , return_index=True )
map_list = map_list[indices]
array_chrom=np.unique( map_list['chrom']) #add new elements to end of the self.chrommosomos
idx_chr=np.in1d(array_chrom,self.chrommosomos)
self.chrommosomos=np.concatenate(( self.chrommosomos , array_chrom[idx_chr==False]))
map_list = np.sort(map_list, order=['chrom', 'position'])
ofile = open(self.outputmap,'w') # open file for writing
print "there are",len(map_list['rs']),"SNPs.\nwriting the",self.outputmap,"file..."
for i in self.chrommosomos:
if i in map_list['chrom']:
idx = map_list['chrom']==i
for i in map_list[:][idx]:
ofile.write(str(i[1])+" "+str(i[0])+" "+str(0)+" "+str(i[2])+"\n")
ofile.close()
def create_ped( self, folders_case, folders_control):
"""Create the .ped file"""
print "\n\n\nPED FILE (",time.asctime(),")\n"
handle = csv.DictReader(open(self.outputmap, "r"),
fieldnames=["chromosome", "rs","morgans", "position"],
delimiter=" ")
for i in handle:
self.all_rs.append(i["rs"])
self.all_rs=np.array(self.all_rs)
ofile = open(self.outputped,'w') # open file for writing
print "\nReading the file to be cases (affected: 2):\n"
for folder in folders_case:
self.write_ped( folder, ofile, "2")
print "\nReading the file to be controls (unaffected: 1):\n"
for folder in folders_control:
self.write_ped(folder, ofile, "1")
ofile.close()
def write_ped(self, dirfilespheno, outputfile, pheno):
"""
read the file inside a folder and parse to write a .ped.
"""
for i in os.listdir(dirfilespheno):
all_rs_ind_tmp = np.array(["0 0"]*len(self.all_rs), dtype='S3') #initialaze every genotype with "0 0"
sex=""
all_names=[]
all_gen=[]
print dirfilespheno+"/"+i,
if "XY" in i:
sex="1"
elif "XX" in i:
sex="2"
else:
sex="9" #sex="other"
try:
snps = sn.parse(dirfilespheno+"/"+i) #take another files
except:
print " ERRO 1"
continue
try:
for cur_snp in snps:
if len(cur_snp.genotype)==2 and cur_snp.genotype in self.valid_alleles:# "--" and cur_snp.genotype != "II" and cur_snp.genotype != "DI":
all_names.append(cur_snp.name)
all_gen.append("%s %s" % (cur_snp.genotype[0], cur_snp.genotype[1]))
except:
print " ERRO 2"
continue
try:
idx = np.flatnonzero(np.in1d(self.all_rs, np.array(all_names)))
except:
print " ERRO 3"
continue
print ""
all_rs_ind_tmp[idx] = np.array(all_gen)
outputfile.write( str(self.Family_ID)+" "+ str(self.Individual_ID)+" "+"0 0 "+sex+" "+ pheno+" ")
for i in all_rs_ind_tmp:
outputfile.write(i+" ")
outputfile.write("\n")
self.Family_ID=self.Family_ID+1
self.Individual_ID=self.Individual_ID+1
def parse_ped (self):
"""
Parse the .ped to avoid more than 2 alleles.
"""
print "\n\nPARSE PED (",time.asctime(),")\n"
print "\nparsing the",self.outputped,"file ..."
#take the file .ped
ifile_ped = open(self.outputped,'r') #folder_test.ped test_all_files_blue_brown.ped zeros( (3,4) )
#create a matrix of the zeros to count how much allelos
ACTG_matrix = np.zeros( (4,len(ifile_ped.readline().split())) )
ifile_ped.close()
#take the file .ped again
ifile_ped = open(self.outputped,'r')
for i in ifile_ped:
line=i.split()
idx_alle= np.array(line)=="A"
ACTG_matrix[0][idx_alle]=1
idx_alle= np.array(line)=="C"
ACTG_matrix[1][idx_alle]=1
idx_alle= np.array(line)=="T"
ACTG_matrix[2][idx_alle]=1
idx_alle= np.array(line)=="G"
ACTG_matrix[3][idx_alle]=1
ifile_ped.close()
ACTG_matrix= ACTG_matrix[:,6:]
self.idx_rem=[]
idx_keep=[]
for c in np.flatnonzero(np.array(range(ACTG_matrix.shape[1]))%2==0):
u=np.sum(ACTG_matrix[:,c:c+2], axis=1)
if len(np.delete(u, np.flatnonzero(u==0))) >2:
self.idx_rem.append(c)
self.idx_rem.append(c+1)
else:
idx_keep.append(c)
idx_keep.append(c+1)
self.idx_rem=np.array(self.idx_rem)
idx_keep=np.array(idx_keep)
ofile_ped = open(self.outputped_parse,'w')
ifile_ped = open(self.outputped,'r')
print "writing the",self.outputped_parse,"file ..."
for l in ifile_ped:
line=np.array(l.split())
ofile_ped.write(line[0]+" "+line[1]+" "+line[2]+" "+line[3]+" "+line[4]+" "+line[5]+" ")
lines=line[6:][idx_keep]
for c in np.flatnonzero(np.array(range( len(lines) ))%2==0) :
ofile_ped.write(lines[c]+" "+lines[c+1]+" ")
ofile_ped.write("\n")
ifile_ped.close()
ofile_ped.close()
def parse_map (self):
"""
Parse the .ped to avoid more than 2 alleles.
"""
print "\n\nPARSE MAP (",time.asctime(),")\n"
print "\nparsing the",self.outputmap ,"file ..."
#take the file .map
dtype = [('chromosome', 'S10'), ('rs', 'S10'), ('morgans', 'S10'),('position', 'S10')]
map_array = np.genfromtxt(self.outputmap, dtype=dtype, delimiter=" ")
#get the idx the columns to be removed in map_array
idx_del_map= self.idx_rem
idx_del_map = idx_del_map[idx_del_map%2 == 0]
idx_del_map=idx_del_map/2
map_array = np.delete(map_array,idx_del_map, axis=0)
print "writing the",self.outputmap_parse ,"file ..."
np.savetxt(self.outputmap_parse,map_array,delimiter=' ',fmt='%s',newline='\n')
def parse_map_ped(self):
"""
Parse the .map and .ped file to avoid more than 2 alleles.
"""
self.parse_ped()
self.parse_map()
if __name__ == '__main__':
# build option parser:
class MyParser(OptionParser):
def format_epilog(self, formatter):
return self.epilog
usage = "usage: python %prog [options] filename\n"
description = """
This program allow us create the .map and .ped files to be used in plink.\n"""
epilog = """
For example:
python map_and_ped.py -m filename.map -p filename.ped --case "folder1 folder2 folder3" --control "folder4 folder5"
INPUT:
"folder1 folder2 folder3"
"folder4 folder5"
OUTPUT
filename.map
filename.ped
If you use the output files filename.map and filename.ped in PLINK. You will get a error similar to below:
ERROR: Locus rs2055204 has >2 alleles:
individual 2 1 has genotype [ C C ]
but we've already seen [ A ] and [ G ]
python map_and_ped.py -m filename.map -p filename.ped --case "folder1 folder2 folder3" --control "folder4 folder5" --omp filename-parsed.map --opp filename-parsed.ped
INPUT:
"folder1 folder2 folder3"
"folder4 folder5"
OUTPUT
filename.map
filename.ped
filename-parsed.map
filename-parsed.ped
You can use the output files filename-parsed.map and filename-parsed.ped in PLINK.
"""
parser = MyParser(usage, description=description,epilog=epilog)
parser.add_option("--case", dest="case", action="store",
help='input - folders with the files representing case. Put the folders inside "". for example: --case "folder1 folder2 folder3"')
parser.add_option("--control", dest="control", action="store",
help='input - folders with the files representing control. Put the folders inside "". for example: --control "folder4 folder5 folder6"')
parser.add_option("-m", "--outfile_map", dest="outfile_map", action="store",
help="output - file name of the .map.")
parser.add_option("-p","--outfile_ped", dest="outfile_ped", action="store",
help="output - file name of the .ped.")
parser.add_option("--omp", dest="outfile_map_parse", action="store",
help="output - file name of the .map to be parsed to be used in plink.")
parser.add_option("--opp", dest="outfile_ped_parse", action="store",
help="output - file name of the .ped to be parsed to be used in plink")
(options, args) = parser.parse_args()
if len(sys.argv) != 9 and len(sys.argv) != 13:
parser.error("incorrect number of arguments. Use -h to help you.")
outfile_map = options.outfile_map
outfile_ped = options.outfile_ped
outfile_map_parse = options.outfile_map_parse
outfile_ped_parse = options.outfile_ped_parse
case = options.case.split()
control = options.control.split()
if (outfile_ped_parse == None or outfile_map_parse == None):
mp = MapAndPed(outfile_map, outfile_ped)
mp.create_map(case, control)
mp.create_ped(case, control)
else:
mp = MapAndPed(outfile_map, outfile_ped, outfile_map_parse, outfile_ped_parse )
mp.create_map(case, control)
mp.create_ped(case, control)
mp.parse_map_ped()
| #!/usr/bin/python
import sn
import sys,string
import numpy as np
import math
import csv
import os.path
from collections import namedtuple
import os
import vcf
import fnmatch
from optparse import OptionParser
import time
class MapAndPed:
"""
This classe allow create and parse .map and .ped files to be used in PLINK.
"""
def __init__(self, outputmap, outputped,outputmap_parse=None, outputped_parse=None):
"""
Initialaze the output names of the files and other variables
"""
#self.outputmap = "Phobia-test5.map"
#self.outputped = "Phobia-test5.ped"
self.outputmap = outputmap
self.outputped = outputped
self.outputmap_parse = outputmap_parse
self.outputped_parse = outputped_parse
self.idx_rem=[]
self.all_rs=[]
self.valid_alleles = ['AA', 'AT', 'AG', 'AC',
'CA', 'CT', 'CG', 'CC',
'TA', 'TT', 'TG', 'TC',
'GA', 'GT', 'GG', 'GC']
self.Family_ID=1
self.Individual_ID=1
self.chrommosomos=np.array(["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","X","Y","MT"])
def create_map(self, folders_case, folders_control):
"""Create the .map file"""
print "\n\nMAP FILE (",time.asctime(),")\n"
dir_list=folders_case[:]
dir_list.extend(folders_control)
files=[]
file_dir={}
map_list=[]
idx=0
for i in dir_list:
files.extend(os.listdir(i)) #it get all files names in a dir
for j in os.listdir(i):
file_dir[j]=i #dictionari with file:dir
print "Reading the files:\n\n",file_dir[files[0]]+"/"+files[0], #parse the first file
try:
snps = sn.parse(file_dir[files[0]]+"/"+files[0])#take the first file
for i in snps: #initialaze rs_list and map_list with the first file
map_list.append((i[0],i[2],i[3]))
except:
print " ERRO 1"
print ""
dtype = [('rs', 'S10'), ('chrom', 'S10'), ('position', int)]
map_list = np.array( map_list, dtype=dtype)
for j in files[1:]:
map_list_tmp=[]
print file_dir[j]+"/"+j,
try:
snps = sn.parse(file_dir[j]+"/"+j) #take another files
except:
print " ERRO 2"
continue
try:
for i in snps:
map_list_tmp.append((i[0],i[2],i[3]))
except:
print " ERRO 3"
continue
print ""
map_list_tmp=np.array(map_list_tmp, dtype=dtype)
map_list=np.array(np.concatenate(( map_list, map_list_tmp)) , dtype=dtype)
u, indices = np.unique( map_list['rs'] , return_index=True )
map_list = map_list[indices]
array_chrom=np.unique( map_list['chrom']) #add new elements to end of the self.chrommosomos
idx_chr=np.in1d(array_chrom,self.chrommosomos)
self.chrommosomos=np.concatenate(( self.chrommosomos , array_chrom[idx_chr==False]))
map_list = np.sort(map_list, order=['chrom', 'position'])
ofile = open(self.outputmap,'w') # open file for writing
print "there are",len(map_list['rs']),"SNPs.\nwriting the",self.outputmap,"file..."
for i in self.chrommosomos:
if i in map_list['chrom']:
idx = map_list['chrom']==i
for i in map_list[:][idx]:
ofile.write(str(i[1])+" "+str(i[0])+" "+str(0)+" "+str(i[2])+"\n")
ofile.close()
def create_ped( self, folders_case, folders_control):
"""Create the .ped file"""
print "\n\n\nPED FILE (",time.asctime(),")\n"
handle = csv.DictReader(open(self.outputmap, "r"),
fieldnames=["chromosome", "rs","morgans", "position"],
delimiter=" ")
for i in handle:
self.all_rs.append(i["rs"])
self.all_rs=np.array(self.all_rs)
ofile = open(self.outputped,'w') # open file for writing
print "\nReading the file to be cases (affected: 2):\n"
for folder in folders_case:
self.write_ped( folder, ofile, "2")
print "\nReading the file to be controls (unaffected: 1):\n"
for folder in folders_control:
self.write_ped(folder, ofile, "1")
ofile.close()
def write_ped(self, dirfilespheno, outputfile, pheno):
"""
read the file inside a folder and parse to write a .ped.
"""
for i in os.listdir(dirfilespheno):
all_rs_ind_tmp = np.array(["0 0"]*len(self.all_rs), dtype='S3') #initialaze every genotype with "0 0"
sex=""
all_names=[]
all_gen=[]
print dirfilespheno+"/"+i,
if "XY" in i:
sex="1"
elif "XX" in i:
sex="2"
else:
sex="9" #sex="other"
try:
snps = sn.parse(dirfilespheno+"/"+i) #take another files
except:
print " ERRO 1"
continue
try:
for cur_snp in snps:
if len(cur_snp.genotype)==2 and cur_snp.genotype in self.valid_alleles:# "--" and cur_snp.genotype != "II" and cur_snp.genotype != "DI":
all_names.append(cur_snp.name)
all_gen.append("%s %s" % (cur_snp.genotype[0], cur_snp.genotype[1]))
except:
print " ERRO 2"
continue
try:
idx = np.flatnonzero(np.in1d(self.all_rs, np.array(all_names)))
except:
print " ERRO 3"
continue
print ""
all_rs_ind_tmp[idx] = np.array(all_gen)
outputfile.write( str(self.Family_ID)+" "+ str(self.Individual_ID)+" "+"0 0 "+sex+" "+ pheno+" ")
for i in all_rs_ind_tmp:
outputfile.write(i+" ")
outputfile.write("\n")
self.Family_ID=self.Family_ID+1
self.Individual_ID=self.Individual_ID+1
def parse_ped (self):
"""
Parse the .ped to avoid more than 2 alleles.
"""
print "\n\nPARSE PED (",time.asctime(),")\n"
print "\nparsing the",self.outputped,"file ..."
#take the file .ped
ifile_ped = open(self.outputped,'r') #folder_test.ped test_all_files_blue_brown.ped zeros( (3,4) )
#create a matrix of the zeros to count how much allelos
ACTG_matrix = np.zeros( (4,len(ifile_ped.readline().split())) )
ifile_ped.close()
#take the file .ped again
ifile_ped = open(self.outputped,'r')
for i in ifile_ped:
line=i.split()
idx_alle= np.array(line)=="A"
ACTG_matrix[0][idx_alle]=1
idx_alle= np.array(line)=="C"
ACTG_matrix[1][idx_alle]=1
idx_alle= np.array(line)=="T"
ACTG_matrix[2][idx_alle]=1
idx_alle= np.array(line)=="G"
ACTG_matrix[3][idx_alle]=1
ifile_ped.close()
ACTG_matrix= ACTG_matrix[:,6:]
self.idx_rem=[]
idx_keep=[]
for c in np.flatnonzero(np.array(range(ACTG_matrix.shape[1]))%2==0):
u=np.sum(ACTG_matrix[:,c:c+2], axis=1)
if len(np.delete(u, np.flatnonzero(u==0))) >2:
self.idx_rem.append(c)
self.idx_rem.append(c+1)
else:
idx_keep.append(c)
idx_keep.append(c+1)
self.idx_rem=np.array(self.idx_rem)
idx_keep=np.array(idx_keep)
ofile_ped = open(self.outputped_parse,'w')
ifile_ped = open(self.outputped,'r')
print "writing the",self.outputped_parse,"file ..."
for l in ifile_ped:
line=np.array(l.split())
ofile_ped.write(line[0]+" "+line[1]+" "+line[2]+" "+line[3]+" "+line[4]+" "+line[5]+" ")
lines=line[6:][idx_keep]
for c in np.flatnonzero(np.array(range( len(lines) ))%2==0) :
ofile_ped.write(lines[c]+" "+lines[c+1]+" ")
ofile_ped.write("\n")
ifile_ped.close()
ofile_ped.close()
def parse_map (self):
"""
Parse the .ped to avoid more than 2 alleles.
"""
print "\n\nPARSE MAP (",time.asctime(),")\n"
print "\nparsing the",self.outputmap ,"file ..."
#take the file .map
dtype = [('chromosome', 'S10'), ('rs', 'S10'), ('morgans', 'S10'),('position', 'S10')]
map_array = np.genfromtxt(self.outputmap, dtype=dtype, delimiter=" ")
#get the idx the columns to be removed in map_array
idx_del_map= self.idx_rem
idx_del_map = idx_del_map[idx_del_map%2 == 0]
idx_del_map=idx_del_map/2
map_array = np.delete(map_array,idx_del_map, axis=0)
print "writing the",self.outputmap_parse ,"file ..."
np.savetxt(self.outputmap_parse,map_array,delimiter=' ',fmt='%s',newline='\n')
def parse_map_ped(self):
"""
Parse the .map and .ped file to avoid more than 2 alleles.
"""
self.parse_ped()
self.parse_map()
if __name__ == '__main__':
# build option parser:
class MyParser(OptionParser):
def format_epilog(self, formatter):
return self.epilog
usage = "usage: python %prog [options] filename\n"
description = """
This program allow us create the .map and .ped files to be used in plink.\n"""
epilog = """
For example:
python map_and_ped.py -m filename.map -p filename.ped --case "folder1 folder2 folder3" --control "folder4 folder5"
INPUT:
"folder1 folder2 folder3"
"folder4 folder5"
OUTPUT
filename.map
filename.ped
If you use the output files filename.map and filename.ped in PLINK. You will get a error similar to below:
ERROR: Locus rs2055204 has >2 alleles:
individual 2 1 has genotype [ C C ]
but we've already seen [ A ] and [ G ]
python map_and_ped.py -m filename.map -p filename.ped --case "folder1 folder2 folder3" --control "folder4 folder5" --omp filename-parsed.map --opp filename-parsed.ped
INPUT:
"folder1 folder2 folder3"
"folder4 folder5"
OUTPUT
filename.map
filename.ped
filename-parsed.map
filename-parsed.ped
You can use the output files filename-parsed.map and filename-parsed.ped in PLINK.
"""
parser = MyParser(usage, description=description,epilog=epilog)
parser.add_option("--case", dest="case", action="store",
help='input - folders with the files representing case. Put the folders inside "". for example: --case "folder1 folder2 folder3"')
parser.add_option("--control", dest="control", action="store",
help='input - folders with the files representing control. Put the folders inside "". for example: --control "folder4 folder5 folder6"')
parser.add_option("-m", "--outfile_map", dest="outfile_map", action="store",
help="output - file name of the .map.")
parser.add_option("-p","--outfile_ped", dest="outfile_ped", action="store",
help="output - file name of the .ped.")
parser.add_option("--omp", dest="outfile_map_parse", action="store",
help="output - file name of the .map to be parsed to be used in plink.")
parser.add_option("--opp", dest="outfile_ped_parse", action="store",
help="output - file name of the .ped to be parsed to be used in plink")
(options, args) = parser.parse_args()
if len(sys.argv) != 9 and len(sys.argv) != 13:
parser.error("incorrect number of arguments. Use -h to help you.")
outfile_map = options.outfile_map
outfile_ped = options.outfile_ped
outfile_map_parse = options.outfile_map_parse
outfile_ped_parse = options.outfile_ped_parse
case = options.case.split()
control = options.control.split()
if (outfile_ped_parse == None or outfile_map_parse == None):
mp = MapAndPed(outfile_map, outfile_ped)
mp.create_map(case, control)
mp.create_ped(case, control)
else:
mp = MapAndPed(outfile_map, outfile_ped, outfile_map_parse, outfile_ped_parse )
mp.create_map(case, control)
mp.create_ped(case, control)
mp.parse_map_ped()
| en | 0.707158 | #!/usr/bin/python This classe allow create and parse .map and .ped files to be used in PLINK. Initialaze the output names of the files and other variables #self.outputmap = "Phobia-test5.map" #self.outputped = "Phobia-test5.ped" Create the .map file #it get all files names in a dir #dictionari with file:dir #parse the first file #take the first file #initialaze rs_list and map_list with the first file #take another files #add new elements to end of the self.chrommosomos # open file for writing Create the .ped file # open file for writing read the file inside a folder and parse to write a .ped. #initialaze every genotype with "0 0" #sex="other" #take another files # "--" and cur_snp.genotype != "II" and cur_snp.genotype != "DI": Parse the .ped to avoid more than 2 alleles. #take the file .ped #folder_test.ped test_all_files_blue_brown.ped zeros( (3,4) ) #create a matrix of the zeros to count how much allelos #take the file .ped again Parse the .ped to avoid more than 2 alleles. #take the file .map #get the idx the columns to be removed in map_array Parse the .map and .ped file to avoid more than 2 alleles. # build option parser: This program allow us create the .map and .ped files to be used in plink.\n For example: python map_and_ped.py -m filename.map -p filename.ped --case "folder1 folder2 folder3" --control "folder4 folder5" INPUT: "folder1 folder2 folder3" "folder4 folder5" OUTPUT filename.map filename.ped If you use the output files filename.map and filename.ped in PLINK. You will get a error similar to below: ERROR: Locus rs2055204 has >2 alleles: individual 2 1 has genotype [ C C ] but we've already seen [ A ] and [ G ] python map_and_ped.py -m filename.map -p filename.ped --case "folder1 folder2 folder3" --control "folder4 folder5" --omp filename-parsed.map --opp filename-parsed.ped INPUT: "folder1 folder2 folder3" "folder4 folder5" OUTPUT filename.map filename.ped filename-parsed.map filename-parsed.ped You can use the output files filename-parsed.map and filename-parsed.ped in PLINK. | 2.253051 | 2 |
show-passwd-hashlen.py | fintanr/hashlength-demo | 0 | 6617123 | <gh_stars>0
#!/usr/bin/env python3
#
# Quick example of hash length versus password length and contents
#
# July 7th 2021, @fintanr
import bcrypt
import string
import random
man_chars = string.ascii_letters + string.digits + string.punctuation
print("Random Password".ljust(60), "Length", "Hash Length")
for i in range(8, 64, 4):
passwd = ( ''.join(random.choice(man_chars) for j in range(i)))
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(passwd.encode('utf8'), salt)
print(passwd.ljust(60), str(len(passwd.encode('utf8'))).ljust(7), len(hashed))
| #!/usr/bin/env python3
#
# Quick example of hash length versus password length and contents
#
# July 7th 2021, @fintanr
import bcrypt
import string
import random
man_chars = string.ascii_letters + string.digits + string.punctuation
print("Random Password".ljust(60), "Length", "Hash Length")
for i in range(8, 64, 4):
passwd = ( ''.join(random.choice(man_chars) for j in range(i)))
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(passwd.encode('utf8'), salt)
print(passwd.ljust(60), str(len(passwd.encode('utf8'))).ljust(7), len(hashed)) | en | 0.736873 | #!/usr/bin/env python3 # # Quick example of hash length versus password length and contents # # July 7th 2021, @fintanr | 3.467875 | 3 |
byob/web-gui/buildyourownbotnet/modules/escalate.py | PandemicPiero/the-hacking-toolkit | 5 | 6617124 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'Escalate Privileges (Build Your Own Botnet)'
# standard library
import os
import sys
import ctypes
# packages
if sys.platform == 'win32':
import win32com.client
# utilities
import util
# globals
packages = ['win32com.client']
platforms = ['win32']
results = {}
usage = 'escalate'
description = """
Attempt UAC bypass to escalate privileges in the current
context on the client host machine
"""
# main
def run(filename):
"""
Attempt to escalate privileges
`Required`
:param str filename: filename to run as administrator
"""
try:
if isinstance(filename, str) and os.path.isfile(filename):
if bool(ctypes.windll.shell32.IsUserAnAdmin() if os.name == 'nt' else os.getuid() == 0):
return "Current user has administrator privileges"
else:
if os.name == 'nt':
return win32com.shell.shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters='{} asadmin'.format(filename))
else:
return "Privilege escalation not yet available on '{}'".format(sys.platform)
else:
return "Error: argument 'filename' must be a valid filename"
except Exception as e:
return "{} erorr: {}".format(__name__, str(e))
| #!/usr/bin/python
# -*- coding: utf-8 -*-
'Escalate Privileges (Build Your Own Botnet)'
# standard library
import os
import sys
import ctypes
# packages
if sys.platform == 'win32':
import win32com.client
# utilities
import util
# globals
packages = ['win32com.client']
platforms = ['win32']
results = {}
usage = 'escalate'
description = """
Attempt UAC bypass to escalate privileges in the current
context on the client host machine
"""
# main
def run(filename):
"""
Attempt to escalate privileges
`Required`
:param str filename: filename to run as administrator
"""
try:
if isinstance(filename, str) and os.path.isfile(filename):
if bool(ctypes.windll.shell32.IsUserAnAdmin() if os.name == 'nt' else os.getuid() == 0):
return "Current user has administrator privileges"
else:
if os.name == 'nt':
return win32com.shell.shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters='{} asadmin'.format(filename))
else:
return "Privilege escalation not yet available on '{}'".format(sys.platform)
else:
return "Error: argument 'filename' must be a valid filename"
except Exception as e:
return "{} erorr: {}".format(__name__, str(e))
| en | 0.774386 | #!/usr/bin/python # -*- coding: utf-8 -*- # standard library # packages # utilities # globals Attempt UAC bypass to escalate privileges in the current context on the client host machine # main Attempt to escalate privileges `Required` :param str filename: filename to run as administrator | 2.820031 | 3 |
hackerrank/Algorithms/Sansa and XOR/solution.py | ATrain951/01.python-com_Qproject | 4 | 6617125 | <filename>hackerrank/Algorithms/Sansa and XOR/solution.py
#!/bin/python3
import os
# Complete the sansaXor function below.
def sansaXor(arr):
import functools
import operator
return 0 if len(arr) % 2 == 0 else functools.reduce(operator.xor, arr[::2])
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = sansaXor(arr)
fptr.write(str(result) + '\n')
fptr.close()
| <filename>hackerrank/Algorithms/Sansa and XOR/solution.py
#!/bin/python3
import os
# Complete the sansaXor function below.
def sansaXor(arr):
import functools
import operator
return 0 if len(arr) % 2 == 0 else functools.reduce(operator.xor, arr[::2])
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = sansaXor(arr)
fptr.write(str(result) + '\n')
fptr.close()
| en | 0.306319 | #!/bin/python3 # Complete the sansaXor function below. | 3.993083 | 4 |
modules/icons.py | jfultz/sublime-GitConflictResolver | 32 | 6617126 | import sublime
_plugin_name = "Git Conflict Resolver"
_icon_folder = "/".join([_plugin_name, "gutter"])
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = "/".join(["..", _icon_folder])
else:
base = "/".join(["Packages", _icon_folder])
extension = ".png"
return "/".join([base, _icons[group] + extension])
| import sublime
_plugin_name = "Git Conflict Resolver"
_icon_folder = "/".join([_plugin_name, "gutter"])
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = "/".join(["..", _icon_folder])
else:
base = "/".join(["Packages", _icon_folder])
extension = ".png"
return "/".join([base, _icons[group] + extension])
| none | 1 | 2.17769 | 2 | |
Dataset/Leetcode/train/7/651.py | kkcookies99/UAST | 0 | 6617127 | <filename>Dataset/Leetcode/train/7/651.py
class Solution:
def XXX(self, x: int) -> int:
'''
先去符号,求绝对值;
再转换
'''
y=abs(x)
z=''
z+=str(y)
while int(z[::-1])>=-2**31 and int(z[::-1])<=2**31-1 and x !=0:
if x>0:
return int(z[::-1])
else:
return 0-int(z[::-1])
return 0
| <filename>Dataset/Leetcode/train/7/651.py
class Solution:
def XXX(self, x: int) -> int:
'''
先去符号,求绝对值;
再转换
'''
y=abs(x)
z=''
z+=str(y)
while int(z[::-1])>=-2**31 and int(z[::-1])<=2**31-1 and x !=0:
if x>0:
return int(z[::-1])
else:
return 0-int(z[::-1])
return 0
| zh | 0.774043 | 先去符号,求绝对值; 再转换 | 2.928515 | 3 |
dashmips/instructions/rd_rs_lbl_instructions.py | nbbeeken/dashmips | 8 | 6617128 | """Instructions that operate on one register."""
from typing import Tuple
from . import mips_instruction
from ..models import MipsProgram
PATTERN = r"{instr_gap}({register}){args_gap}({register}){args_gap}({label})"
def parse(arg: Tuple[str, str, str, str, str]) -> Tuple[str, str, str]:
"""Two Register and Immediate instructions Parser."""
return (arg[2], arg[3], arg[4])
@mips_instruction(PATTERN, parse)
def beq(program: MipsProgram, rs: str, rt: str, label: str):
"""Branch to label if Reg[rs] == Reg[rt]."""
if program.registers[rs] == program.registers[rt]:
program.registers["pc"] = program.labels[label].value - 1
@mips_instruction(PATTERN, parse)
def bne(program: MipsProgram, rs: str, rt: str, label: str):
"""Branch to label if Reg[rs] != Reg[rt]."""
if program.registers[rs] != program.registers[rt]:
program.registers["pc"] = program.labels[label].value - 1
| """Instructions that operate on one register."""
from typing import Tuple
from . import mips_instruction
from ..models import MipsProgram
PATTERN = r"{instr_gap}({register}){args_gap}({register}){args_gap}({label})"
def parse(arg: Tuple[str, str, str, str, str]) -> Tuple[str, str, str]:
"""Two Register and Immediate instructions Parser."""
return (arg[2], arg[3], arg[4])
@mips_instruction(PATTERN, parse)
def beq(program: MipsProgram, rs: str, rt: str, label: str):
"""Branch to label if Reg[rs] == Reg[rt]."""
if program.registers[rs] == program.registers[rt]:
program.registers["pc"] = program.labels[label].value - 1
@mips_instruction(PATTERN, parse)
def bne(program: MipsProgram, rs: str, rt: str, label: str):
"""Branch to label if Reg[rs] != Reg[rt]."""
if program.registers[rs] != program.registers[rt]:
program.registers["pc"] = program.labels[label].value - 1
| en | 0.726025 | Instructions that operate on one register. Two Register and Immediate instructions Parser. Branch to label if Reg[rs] == Reg[rt]. Branch to label if Reg[rs] != Reg[rt]. | 3.374985 | 3 |
core/tools/explorer.py | vruello/anssi-project | 0 | 6617129 | <gh_stars>0
# -*- coding: utf-8 -*-
from metasploit.msfrpc import MsfRpcClient
import re
import urllib
import time
import anssi.settings
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
import os
import shutil
def ls_files_parser(lsret):
lines = lsret.lstrip().split("\n")
files = []
# Skip errors
while len(lines) > 0 and len(lines[0]) > 0 and lines[0].split()[0] != 'Listing:':
lines.pop(0)
if (len(lines) <= 5):
return files
# Parse files
for line in lines[5:len(lines) - 2]:
l = line.split()
if len(l) < 7:
break
#if re.match(r"40777", l[0]) == None:
files.append({
'name': (" ".join(l[6:])),
'urlencoded_name': urllib.quote_plus(" ".join(l[6:])),
'permission': l[0],
'size': l[1],
'type': l[2],
'last_modified': l[3],
'hour': l[4],
'timezone': l[5]
})
return files
def ls_pwd_parser(lsret):
lines = lsret.lstrip().split("\n")
for line in lines:
l = line.split()
if len(l) > 0 and "Listing:" in l[0]:
return " ".join(l[1:]).replace('\\', '/')
return ""
def add_routing_files(files):
files.insert(0, {'name': '.', 'urlencoded_name': urllib.quote_plus('.'), 'type': 'dir'})
files.insert(0, {'name': '..', 'urlencoded_name': urllib.quote_plus('..'), 'type': 'dir'})
def ls(shell):
shell.write('ls\n')
result = ''
result = shell.read()
error = False
if "[-] stdapi_fs_ls: Operation failed: Access is denied." in result:
error = True
return (ls_pwd_parser(result), ls_files_parser(result), error)
def cd(shell, arg):
shell.write("cd \"" + arg + "\"")
time.sleep(0.5)
def download(shell, name):
timestamp = int(time.time())
path = str(timestamp)
full_path = os.path.join(anssi.settings.MEDIA_ROOT, path)
shell.write('download "' + name + '" "' + full_path + '"')
ret = shell.read()
while not "download" in ret:
time.sleep(0.1)
ret = shell.read()
file_path = os.path.join(anssi.settings.MEDIA_ROOT, path + '/' + name)
if os.path.exists(file_path):
fh = open(file_path, 'rb')
data = fh.read()
response = HttpResponse(content_type="application/download")
response['Content-Disposition'] = 'attachment; filename=' + name
response.write(data)
shutil.rmtree(os.path.join(anssi.settings.MEDIA_ROOT, path))
return response
def upload(shell, uploaded_file):
fs = FileSystemStorage()
filename = fs.save(uploaded_file.name, uploaded_file)
file_path = os.path.join(anssi.settings.MEDIA_ROOT, filename)
shell.write('upload "' + file_path + '" .')
ret = shell.read()
succeed = False
while not "uploaded" in ret and not "Operation failed" in ret:
time.sleep(0.1)
ret = shell.read()
if "uploaded" in ret:
succeed = True
fs.delete(file_path)
return succeed
def rm(shell, name):
shell.write('rm "' + name + '"')
time.sleep(0.5)
def rmdir(shell, name):
shell.write('rmdir "' + name + '"')
time.sleep(0.5)
| # -*- coding: utf-8 -*-
from metasploit.msfrpc import MsfRpcClient
import re
import urllib
import time
import anssi.settings
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
import os
import shutil
def ls_files_parser(lsret):
lines = lsret.lstrip().split("\n")
files = []
# Skip errors
while len(lines) > 0 and len(lines[0]) > 0 and lines[0].split()[0] != 'Listing:':
lines.pop(0)
if (len(lines) <= 5):
return files
# Parse files
for line in lines[5:len(lines) - 2]:
l = line.split()
if len(l) < 7:
break
#if re.match(r"40777", l[0]) == None:
files.append({
'name': (" ".join(l[6:])),
'urlencoded_name': urllib.quote_plus(" ".join(l[6:])),
'permission': l[0],
'size': l[1],
'type': l[2],
'last_modified': l[3],
'hour': l[4],
'timezone': l[5]
})
return files
def ls_pwd_parser(lsret):
lines = lsret.lstrip().split("\n")
for line in lines:
l = line.split()
if len(l) > 0 and "Listing:" in l[0]:
return " ".join(l[1:]).replace('\\', '/')
return ""
def add_routing_files(files):
files.insert(0, {'name': '.', 'urlencoded_name': urllib.quote_plus('.'), 'type': 'dir'})
files.insert(0, {'name': '..', 'urlencoded_name': urllib.quote_plus('..'), 'type': 'dir'})
def ls(shell):
shell.write('ls\n')
result = ''
result = shell.read()
error = False
if "[-] stdapi_fs_ls: Operation failed: Access is denied." in result:
error = True
return (ls_pwd_parser(result), ls_files_parser(result), error)
def cd(shell, arg):
shell.write("cd \"" + arg + "\"")
time.sleep(0.5)
def download(shell, name):
timestamp = int(time.time())
path = str(timestamp)
full_path = os.path.join(anssi.settings.MEDIA_ROOT, path)
shell.write('download "' + name + '" "' + full_path + '"')
ret = shell.read()
while not "download" in ret:
time.sleep(0.1)
ret = shell.read()
file_path = os.path.join(anssi.settings.MEDIA_ROOT, path + '/' + name)
if os.path.exists(file_path):
fh = open(file_path, 'rb')
data = fh.read()
response = HttpResponse(content_type="application/download")
response['Content-Disposition'] = 'attachment; filename=' + name
response.write(data)
shutil.rmtree(os.path.join(anssi.settings.MEDIA_ROOT, path))
return response
def upload(shell, uploaded_file):
fs = FileSystemStorage()
filename = fs.save(uploaded_file.name, uploaded_file)
file_path = os.path.join(anssi.settings.MEDIA_ROOT, filename)
shell.write('upload "' + file_path + '" .')
ret = shell.read()
succeed = False
while not "uploaded" in ret and not "Operation failed" in ret:
time.sleep(0.1)
ret = shell.read()
if "uploaded" in ret:
succeed = True
fs.delete(file_path)
return succeed
def rm(shell, name):
shell.write('rm "' + name + '"')
time.sleep(0.5)
def rmdir(shell, name):
shell.write('rmdir "' + name + '"')
time.sleep(0.5) | en | 0.398499 | # -*- coding: utf-8 -*- # Skip errors # Parse files #if re.match(r"40777", l[0]) == None: | 2.021543 | 2 |
bloxel/terminal_colors.py | Pebaz/bloxel | 9 | 6617130 | <filename>bloxel/terminal_colors.py
"""
A collection of constants for use in making the usage of terminal coloring as
simple as possible.
These constants can be used very easily along with the `format` function.
print("{0}Hello{1} again {0}World!{1}".format(_CLRfb, _CLRreset))
"""
import colorama
colorama.init(convert=True)
# Foreground Colors
_CLRfbl = colorama.Fore.BLACK
_CLRfr = colorama.Fore.RED
_CLRfg = colorama.Fore.GREEN
_CLRfy = colorama.Fore.YELLOW
_CLRfb = colorama.Fore.BLUE
_CLRfm = colorama.Fore.MAGENTA
_CLRfc = colorama.Fore.CYAN
_CLRfw = colorama.Fore.WHITE
_CLRfreset = colorama.Fore.RESET
# Background Colors
_CLRbbl = colorama.Back.BLACK
_CLRbr = colorama.Back.RED
_CLRbg = colorama.Back.GREEN
_CLRby = colorama.Back.YELLOW
_CLRbb = colorama.Back.BLUE
_CLRbm = colorama.Back.MAGENTA
_CLRbc = colorama.Back.CYAN
_CLRbw = colorama.Back.WHITE
_CLRbreset = colorama.Back.RESET
# Styles
_CLRreset = colorama.Style.RESET_ALL
__all__ = [i for i in dir() if i.startswith('_CLR')]
| <filename>bloxel/terminal_colors.py
"""
A collection of constants for use in making the usage of terminal coloring as
simple as possible.
These constants can be used very easily along with the `format` function.
print("{0}Hello{1} again {0}World!{1}".format(_CLRfb, _CLRreset))
"""
import colorama
colorama.init(convert=True)
# Foreground Colors
_CLRfbl = colorama.Fore.BLACK
_CLRfr = colorama.Fore.RED
_CLRfg = colorama.Fore.GREEN
_CLRfy = colorama.Fore.YELLOW
_CLRfb = colorama.Fore.BLUE
_CLRfm = colorama.Fore.MAGENTA
_CLRfc = colorama.Fore.CYAN
_CLRfw = colorama.Fore.WHITE
_CLRfreset = colorama.Fore.RESET
# Background Colors
_CLRbbl = colorama.Back.BLACK
_CLRbr = colorama.Back.RED
_CLRbg = colorama.Back.GREEN
_CLRby = colorama.Back.YELLOW
_CLRbb = colorama.Back.BLUE
_CLRbm = colorama.Back.MAGENTA
_CLRbc = colorama.Back.CYAN
_CLRbw = colorama.Back.WHITE
_CLRbreset = colorama.Back.RESET
# Styles
_CLRreset = colorama.Style.RESET_ALL
__all__ = [i for i in dir() if i.startswith('_CLR')]
| en | 0.806724 | A collection of constants for use in making the usage of terminal coloring as simple as possible. These constants can be used very easily along with the `format` function. print("{0}Hello{1} again {0}World!{1}".format(_CLRfb, _CLRreset)) # Foreground Colors # Background Colors # Styles | 2.980677 | 3 |
hangar_{{cookiecutter.plugin_name}}/hangar_{{cookiecutter.plugin_name}}/__init__.py | tensorwerk/hangar-external-plugin-cookiecutter | 0 | 6617131 | <filename>hangar_{{cookiecutter.plugin_name}}/hangar_{{cookiecutter.plugin_name}}/__init__.py
from .plugin import Hangar{{cookiecutter.plugin_name}}
| <filename>hangar_{{cookiecutter.plugin_name}}/hangar_{{cookiecutter.plugin_name}}/__init__.py
from .plugin import Hangar{{cookiecutter.plugin_name}}
| none | 1 | 1.125488 | 1 | |
gsodpy/gsoDownloader/__init__.py | wino6687/gsodpy | 1 | 6617132 | name = 'gsoDownloader'
| name = 'gsoDownloader'
| none | 1 | 1.242444 | 1 | |
CreateTableFromDatabase.py | LiquidFun/Reddit-GeoGuessr-Tracking-Bot | 0 | 6617133 | <filename>CreateTableFromDatabase.py
import sqlite3
import operator
import sys, os
from .AddScoresToDatabase import getTitle
from .AddScoresToDatabase import getDate
from .InitDatabase import getRedditInstance
from .AddScoresToDatabase import getSubmissionDateFromDatabase
# Create a table with the rankings from the local database for a series up until a specific submission excluding that submission
def getRankingsFromDatabase(submission):
# Connect to database
database = sqlite3.connect(os.path.join(os.path.dirname(__file__), "database.db"))
cursor = database.cursor()
# Create a set with all the usernames in that series
nameSet = set()
for row in cursor.execute("SELECT Place1, Place2, Place3 FROM ChallengeRankings WHERE SeriesTitle = ? AND Date < ?", [getTitle(submission), str(getSubmissionDateFromDatabase(submission))]):
# This is for the entirety of the table #for row in cursor.execute("SELECT Place1, Place2, Place3 FROM ChallengeRankings"):
for val in row:
if val is not '':
for author in val.split('|'):
nameSet.add(author)
nameList = [name for name in nameSet]
table = [[name, 0, 0, 0] for name in nameList]
# Iterate through every post in the series and increment the winners in the table
for i in range(1, 4):
for row in cursor.execute("SELECT Place" + str(i) + " FROM ChallengeRankings WHERE SeriesTitle = ? AND Date < ?", [getTitle(submission), str(getSubmissionDateFromDatabase(submission))]):
# This is for the entirety of the table #for row in cursor.execute("SELECT Place" + str(i) + " FROM ChallengeRankings"):
for val in row:
if val is not '':
for author in val.split('|'):
table[nameList.index(author)][i] += 1
table.sort(reverse = True, key = operator.itemgetter(1, 2, 3))
database.close()
#print(table)
return table
def getTableOfSeriesGamesFromDatabase(SeriesTitle):
# Connect to database
database = sqlite3.connect(os.path.join(os.path.dirname(__file__), "database.db"))
cursor = database.cursor()
table = []
for row in cursor.execute("SELECT SubmissionID, SubmissionTitle, Place1, Place2, Place3 FROM ChallengeRankings WHERE SeriesTitle = ?", [SeriesTitle]):
table.append(row)
database.close()
#print(table)
return table
if __name__ == '__main__':
#reddit = getRedditInstance()
#print(getRankingsFromDatabase(reddit.submission(id = '6fe4fi')))
print(getTableOfSeriesGamesFromDatabase("roadslesstravelled"))
| <filename>CreateTableFromDatabase.py
import sqlite3
import operator
import sys, os
from .AddScoresToDatabase import getTitle
from .AddScoresToDatabase import getDate
from .InitDatabase import getRedditInstance
from .AddScoresToDatabase import getSubmissionDateFromDatabase
# Create a table with the rankings from the local database for a series up until a specific submission excluding that submission
def getRankingsFromDatabase(submission):
# Connect to database
database = sqlite3.connect(os.path.join(os.path.dirname(__file__), "database.db"))
cursor = database.cursor()
# Create a set with all the usernames in that series
nameSet = set()
for row in cursor.execute("SELECT Place1, Place2, Place3 FROM ChallengeRankings WHERE SeriesTitle = ? AND Date < ?", [getTitle(submission), str(getSubmissionDateFromDatabase(submission))]):
# This is for the entirety of the table #for row in cursor.execute("SELECT Place1, Place2, Place3 FROM ChallengeRankings"):
for val in row:
if val is not '':
for author in val.split('|'):
nameSet.add(author)
nameList = [name for name in nameSet]
table = [[name, 0, 0, 0] for name in nameList]
# Iterate through every post in the series and increment the winners in the table
for i in range(1, 4):
for row in cursor.execute("SELECT Place" + str(i) + " FROM ChallengeRankings WHERE SeriesTitle = ? AND Date < ?", [getTitle(submission), str(getSubmissionDateFromDatabase(submission))]):
# This is for the entirety of the table #for row in cursor.execute("SELECT Place" + str(i) + " FROM ChallengeRankings"):
for val in row:
if val is not '':
for author in val.split('|'):
table[nameList.index(author)][i] += 1
table.sort(reverse = True, key = operator.itemgetter(1, 2, 3))
database.close()
#print(table)
return table
def getTableOfSeriesGamesFromDatabase(SeriesTitle):
# Connect to database
database = sqlite3.connect(os.path.join(os.path.dirname(__file__), "database.db"))
cursor = database.cursor()
table = []
for row in cursor.execute("SELECT SubmissionID, SubmissionTitle, Place1, Place2, Place3 FROM ChallengeRankings WHERE SeriesTitle = ?", [SeriesTitle]):
table.append(row)
database.close()
#print(table)
return table
if __name__ == '__main__':
#reddit = getRedditInstance()
#print(getRankingsFromDatabase(reddit.submission(id = '6fe4fi')))
print(getTableOfSeriesGamesFromDatabase("roadslesstravelled"))
| en | 0.790175 | # Create a table with the rankings from the local database for a series up until a specific submission excluding that submission # Connect to database # Create a set with all the usernames in that series # This is for the entirety of the table #for row in cursor.execute("SELECT Place1, Place2, Place3 FROM ChallengeRankings"): # Iterate through every post in the series and increment the winners in the table # This is for the entirety of the table #for row in cursor.execute("SELECT Place" + str(i) + " FROM ChallengeRankings"): #print(table) # Connect to database #print(table) #reddit = getRedditInstance() #print(getRankingsFromDatabase(reddit.submission(id = '6fe4fi'))) | 3.23815 | 3 |
setup.py | Susanna-Salata/clean-folder | 0 | 6617134 | from setuptools import setup, find_namespace_packages
setup(
name='clean-folder',
version='1.0.0',
description='Sorting files in a folder',
url='https://github.com/Susanna-Salata/clean_folder',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=find_namespace_packages(),
install_requires=[],
entry_points={'console_scripts': ['clean-folder = clean_folder.clean:sorter']}
)
| from setuptools import setup, find_namespace_packages
setup(
name='clean-folder',
version='1.0.0',
description='Sorting files in a folder',
url='https://github.com/Susanna-Salata/clean_folder',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=find_namespace_packages(),
install_requires=[],
entry_points={'console_scripts': ['clean-folder = clean_folder.clean:sorter']}
)
| none | 1 | 1.36479 | 1 | |
actor_critic_layer/Curiosity.py | YangRui2015/Sparse-Reward-Algorithms | 44 | 6617135 | import tensorflow as tf
import numpy as np
from .utils import create_nn
class ForwardDynamics:
def __init__(self, state_dim, action_dim, name="", learning_rate=1e-5):
self.state_dim = state_dim
self.action_dim = action_dim
self.input_dim = state_dim + action_dim
self.lr = learning_rate
self.name = name
self._build_net()
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer())
def _build_net(self):
self.state = tf.placeholder(tf.float32, [None, self.state_dim], name=self.name + 'state') # input
self.next_state = tf.placeholder(tf.float32, [None, self.state_dim], name=self.name + 'next_state')
self.action = tf.placeholder(tf.float32, [None, self.action_dim], name=self.name + 'action')
self.input = tf.concat((self.state, self.action),axis=-1)
with tf.variable_scope(self.name + 'train_net'):
l1 = create_nn(self.input, self.input_dim, 64, relu=True, trainable=True, name='l1')
self.train_net_output = create_nn(l1, 64, self.state_dim,relu=False, trainable=True, name='output')
self.loss = tf.reduce_mean(tf.squared_difference(self.train_net_output, self.next_state)) # loss
self.intrinsic_reward = tf.reduce_mean(tf.squared_difference(self.train_net_output, self.next_state), axis=-1)
self._train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss)
def train(self, state, action, next_state):
loss, train_op = self.sess.run([self.loss, self._train_op], feed_dict={self.state: state,self.action: action,self.next_state: next_state })
return loss
def get_intrinsic_reward(self, state, action, next_state):
return self.sess.run(self.intrinsic_reward, feed_dict={
self.state:state,
self.action:action,
self.next_state:next_state
})
def predict(self, state, action):
return self.sess.run(self.train_net_output, feed_dict={
self.state: state,
self.action:action
})
| import tensorflow as tf
import numpy as np
from .utils import create_nn
class ForwardDynamics:
def __init__(self, state_dim, action_dim, name="", learning_rate=1e-5):
self.state_dim = state_dim
self.action_dim = action_dim
self.input_dim = state_dim + action_dim
self.lr = learning_rate
self.name = name
self._build_net()
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer())
def _build_net(self):
self.state = tf.placeholder(tf.float32, [None, self.state_dim], name=self.name + 'state') # input
self.next_state = tf.placeholder(tf.float32, [None, self.state_dim], name=self.name + 'next_state')
self.action = tf.placeholder(tf.float32, [None, self.action_dim], name=self.name + 'action')
self.input = tf.concat((self.state, self.action),axis=-1)
with tf.variable_scope(self.name + 'train_net'):
l1 = create_nn(self.input, self.input_dim, 64, relu=True, trainable=True, name='l1')
self.train_net_output = create_nn(l1, 64, self.state_dim,relu=False, trainable=True, name='output')
self.loss = tf.reduce_mean(tf.squared_difference(self.train_net_output, self.next_state)) # loss
self.intrinsic_reward = tf.reduce_mean(tf.squared_difference(self.train_net_output, self.next_state), axis=-1)
self._train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss)
def train(self, state, action, next_state):
loss, train_op = self.sess.run([self.loss, self._train_op], feed_dict={self.state: state,self.action: action,self.next_state: next_state })
return loss
def get_intrinsic_reward(self, state, action, next_state):
return self.sess.run(self.intrinsic_reward, feed_dict={
self.state:state,
self.action:action,
self.next_state:next_state
})
def predict(self, state, action):
return self.sess.run(self.train_net_output, feed_dict={
self.state: state,
self.action:action
})
| en | 0.312663 | # input # loss | 2.647703 | 3 |
apps/repositories/forms.py | xobb1t/djangodash12 | 0 | 6617136 | <gh_stars>0
from django import forms
from .models import Repo
from .utils import repo_exists
class RepoForm(forms.ModelForm):
class Meta:
model = Repo
fields = ('name', 'cname',)
def __init__(self, repo_user=None, *args, **kwargs):
self.repo_user = repo_user
super(RepoForm, self).__init__(*args, **kwargs)
def clean_name(self):
access_token = self.repo_user.access_token
login = self.repo_user.username
repo = self.cleaned_data['name']
if repo_exists(access_token, login, repo):
raise forms.ValidationError('{0} exists!'.format(repo))
return repo
| from django import forms
from .models import Repo
from .utils import repo_exists
class RepoForm(forms.ModelForm):
class Meta:
model = Repo
fields = ('name', 'cname',)
def __init__(self, repo_user=None, *args, **kwargs):
self.repo_user = repo_user
super(RepoForm, self).__init__(*args, **kwargs)
def clean_name(self):
access_token = self.repo_user.access_token
login = self.repo_user.username
repo = self.cleaned_data['name']
if repo_exists(access_token, login, repo):
raise forms.ValidationError('{0} exists!'.format(repo))
return repo | none | 1 | 2.347792 | 2 | |
covidata/persistencia/disco_virtual.py | SecexSaudeTCU/CoviDATA | 5 | 6617137 | <reponame>SecexSaudeTCU/CoviDATA<gh_stars>1-10
import configparser
import io
from webdav3.client import Client
from covidata import config
def salvar(caminho_arquivo, nome_arquivo='UFs.xlsx'):
cfg = configparser.ConfigParser(interpolation=None)
with io.open(str(config.arquivo_config_webdav), mode='r', encoding='utf-8') as fp:
cfg.read_file(fp)
options = {
'webdav_hostname': cfg['webdav']['hostname'],
'webdav_login': cfg['webdav']['login'],
'webdav_password': cfg['webdav']['password']
}
pasta_virtual = cfg['webdav']['pasta_virtual']
cliente = Client(options)
cliente.verify = False
cliente.upload_sync(remote_path=pasta_virtual + '/' + nome_arquivo, local_path=caminho_arquivo)
print('Upload concluído. Listando conteúdo do diretório remoto...')
print(cliente.list(pasta_virtual))
| import configparser
import io
from webdav3.client import Client
from covidata import config
def salvar(caminho_arquivo, nome_arquivo='UFs.xlsx'):
cfg = configparser.ConfigParser(interpolation=None)
with io.open(str(config.arquivo_config_webdav), mode='r', encoding='utf-8') as fp:
cfg.read_file(fp)
options = {
'webdav_hostname': cfg['webdav']['hostname'],
'webdav_login': cfg['webdav']['login'],
'webdav_password': cfg['webdav']['password']
}
pasta_virtual = cfg['webdav']['pasta_virtual']
cliente = Client(options)
cliente.verify = False
cliente.upload_sync(remote_path=pasta_virtual + '/' + nome_arquivo, local_path=caminho_arquivo)
print('Upload concluído. Listando conteúdo do diretório remoto...')
print(cliente.list(pasta_virtual)) | none | 1 | 2.334504 | 2 | |
docs/kbd/search.py | snehilvj/dmc-docs | 6 | 6617138 | import dash_mantine_components as dmc
component = dmc.TextInput(
placeholder="Search",
rightSectionWidth=80,
rightSection=[dmc.Kbd("Ctrl + K")],
style={"width": 400},
)
| import dash_mantine_components as dmc
component = dmc.TextInput(
placeholder="Search",
rightSectionWidth=80,
rightSection=[dmc.Kbd("Ctrl + K")],
style={"width": 400},
)
| none | 1 | 1.840533 | 2 | |
streamlit_app/visualize/build_plot.py | JeyDi/STN | 0 | 6617139 | import networkx as nx
import pandas as pd
import plotly.graph_objects as go
from plotly.offline import plot
import pickle
from visualize.layout import build_graph
import streamlit as st
def step_graph(G, df, step):
"""
Prende il grafo e per ogni step della simulazione prende i risultati della simulazione di quello step e aggiunge gli attributi ai nodi
"""
try:
print(f"Start editing the plot for the step: {step}")
df_id = df[df["key"] == "id"].reset_index()
df_infected_type = df[df["key"] == "infected_type"].reset_index()
df_directed = df[df['key'] == 'directed' ].reset_index()
df_type = df[df["key"] == "type"] # DF with opinion leader and bot
df_type["agent_id"] = df_type["agent_id"].astype("str")
df_type = df_type.set_index("agent_id")
nx.set_node_attributes(G, df_type["value"].to_dict(), "type")
i = 0
while i <= step:
step_df = df_id[df_id["t_step"] == i]
step_df["agent_id"] = step_df["agent_id"].astype("str")
step_df = step_df.set_index("agent_id")
nx.set_node_attributes(G, step_df["value"].to_dict(), "state")
step_infected_type = df_infected_type[df_infected_type["t_step"] == i]
step_infected_type["agent_id"] = step_infected_type["agent_id"].astype(
"str"
)
step_infected_type = step_infected_type.set_index("agent_id")
nx.set_node_attributes(
G, step_infected_type["value"].to_dict(), "infected_type"
)
step_directed = df_directed[df_directed['t_step'] == i]
step_directed['agent_id'] = step_directed['agent_id'].astype(
"str"
)
step_directed = step_directed.set_index('agent_id')
nx.set_node_attributes(
G, step_directed['value'].to_dict(), 'directed'
)
i = i + 1 # INTERVAL IN AGENT PARAMETER
result = G.copy()
print(f"Graph fixed for the step: {step}")
return result
except Exception as message:
print(f"Impossible to edit the graph: {message}")
return None
def generate_graph_plot(
G_path,
simulation_data_path,
simulation_name,
G_step_iterations=5,
sprint_layout_calc=False,
):
# Import data
try:
G = nx.read_gexf(G_path)
df = pd.read_csv(simulation_data_path)
print("data succesfully loaded")
except Exception as message:
print(f"Impossibile to read data: {message}")
try:
if is_simulation_based_on_500(simulation_name):
layout_pickle_filename = "./data/serialization/G_node_poss_layout.pkl"
# Shared layout
if sprint_layout_calc:
G_node_pos = nx.spring_layout(G)
with open(layout_pickle_filename, "wb") as output:
pickle.dump(G_node_pos, output, pickle.HIGHEST_PROTOCOL)
load = False
print("Spring graph layout calcolated and stored")
else:
##load pickle object
with open(layout_pickle_filename, "rb") as input:
G_node_pos = pickle.load(input)
load = True
print("Spring graph layout loaded from pickle file")
except Exception as message:
if load:
print(f"Impossibile to load the pickle file: {message}")
elif not load:
print(f"Impossible to calc and save the pickle file: {message}")
for i in range(G_step_iterations):
print(f"Start generating the plot: {G_step_iterations}")
G_step = None
G_step = step_graph(G, df, i)
nx.write_gexf(G_step, f"./data/output/G_{simulation_name}_step{i}.gexf")
if is_simulation_based_on_500(simulation_name):
result_graph = build_graph(G_step, G_node_pos, i)
st.plotly_chart(result_graph, use_container_width=True)
print(f"{simulation_name} - STEP {i} DONE")
print("\nGraph plot and statistics calculated succesfully")
return True
def is_simulation_based_on_500(simulation_name):
return simulation_name.split("_")[1] == "500"
| import networkx as nx
import pandas as pd
import plotly.graph_objects as go
from plotly.offline import plot
import pickle
from visualize.layout import build_graph
import streamlit as st
def step_graph(G, df, step):
"""
Prende il grafo e per ogni step della simulazione prende i risultati della simulazione di quello step e aggiunge gli attributi ai nodi
"""
try:
print(f"Start editing the plot for the step: {step}")
df_id = df[df["key"] == "id"].reset_index()
df_infected_type = df[df["key"] == "infected_type"].reset_index()
df_directed = df[df['key'] == 'directed' ].reset_index()
df_type = df[df["key"] == "type"] # DF with opinion leader and bot
df_type["agent_id"] = df_type["agent_id"].astype("str")
df_type = df_type.set_index("agent_id")
nx.set_node_attributes(G, df_type["value"].to_dict(), "type")
i = 0
while i <= step:
step_df = df_id[df_id["t_step"] == i]
step_df["agent_id"] = step_df["agent_id"].astype("str")
step_df = step_df.set_index("agent_id")
nx.set_node_attributes(G, step_df["value"].to_dict(), "state")
step_infected_type = df_infected_type[df_infected_type["t_step"] == i]
step_infected_type["agent_id"] = step_infected_type["agent_id"].astype(
"str"
)
step_infected_type = step_infected_type.set_index("agent_id")
nx.set_node_attributes(
G, step_infected_type["value"].to_dict(), "infected_type"
)
step_directed = df_directed[df_directed['t_step'] == i]
step_directed['agent_id'] = step_directed['agent_id'].astype(
"str"
)
step_directed = step_directed.set_index('agent_id')
nx.set_node_attributes(
G, step_directed['value'].to_dict(), 'directed'
)
i = i + 1 # INTERVAL IN AGENT PARAMETER
result = G.copy()
print(f"Graph fixed for the step: {step}")
return result
except Exception as message:
print(f"Impossible to edit the graph: {message}")
return None
def generate_graph_plot(
G_path,
simulation_data_path,
simulation_name,
G_step_iterations=5,
sprint_layout_calc=False,
):
# Import data
try:
G = nx.read_gexf(G_path)
df = pd.read_csv(simulation_data_path)
print("data succesfully loaded")
except Exception as message:
print(f"Impossibile to read data: {message}")
try:
if is_simulation_based_on_500(simulation_name):
layout_pickle_filename = "./data/serialization/G_node_poss_layout.pkl"
# Shared layout
if sprint_layout_calc:
G_node_pos = nx.spring_layout(G)
with open(layout_pickle_filename, "wb") as output:
pickle.dump(G_node_pos, output, pickle.HIGHEST_PROTOCOL)
load = False
print("Spring graph layout calcolated and stored")
else:
##load pickle object
with open(layout_pickle_filename, "rb") as input:
G_node_pos = pickle.load(input)
load = True
print("Spring graph layout loaded from pickle file")
except Exception as message:
if load:
print(f"Impossibile to load the pickle file: {message}")
elif not load:
print(f"Impossible to calc and save the pickle file: {message}")
for i in range(G_step_iterations):
print(f"Start generating the plot: {G_step_iterations}")
G_step = None
G_step = step_graph(G, df, i)
nx.write_gexf(G_step, f"./data/output/G_{simulation_name}_step{i}.gexf")
if is_simulation_based_on_500(simulation_name):
result_graph = build_graph(G_step, G_node_pos, i)
st.plotly_chart(result_graph, use_container_width=True)
print(f"{simulation_name} - STEP {i} DONE")
print("\nGraph plot and statistics calculated succesfully")
return True
def is_simulation_based_on_500(simulation_name):
return simulation_name.split("_")[1] == "500"
| it | 0.932605 | Prende il grafo e per ogni step della simulazione prende i risultati della simulazione di quello step e aggiunge gli attributi ai nodi # DF with opinion leader and bot # INTERVAL IN AGENT PARAMETER # Import data # Shared layout ##load pickle object | 2.911489 | 3 |
qmt/geometry/builder_2d.py | merrittlosert/qmt | 31 | 6617140 | <reponame>merrittlosert/qmt<filename>qmt/geometry/builder_2d.py<gh_stars>10-100
from typing import Dict, List, Optional, Union
from .geo_2d_data import Geo2DData
from shapely.geometry import LineString, Polygon
def build_2d_geometry(
parts: Dict[str, List[float]],
edges: Dict[str, List[float]],
lunit: str = "nm",
build_order: Optional[List[str]] = None,
) -> Geo2DData:
"""Build a geometry in 2D.
Parameters
----------
parts : dict
Dictionary for holding the 2D parts, of the form
{'part_name':list of 2d points}.
edges : dict
Dictionary of 2D edges, of the form:
{'edge_name':list of 2d points}.
lunit : str
length_unit (nm).
(Default value = "nm")
build_order : list
None or a list of all parts, determining the build order. Items on
the left are highest priority and items on the right are lowest.
If None is given (default), then build order is determined just
taken to be the order of the parts and edges.
(Default value = None)
Returns
-------
Geo2DData instance
"""
geo_2d = Geo2DData()
if build_order is None:
build_order = list(parts)
# Set up the complete build order:
for part in parts:
if part not in build_order:
build_order.append(part)
for edge in edges:
if edge not in build_order:
build_order.append(edge)
for object_name in build_order:
if object_name in parts:
geo_2d.add_part(object_name, Polygon(parts[object_name]))
elif object_name in edges:
geo_2d.add_part(object_name, LineString(edges[object_name]))
else:
raise ValueError(
f"Object of name {object_name} was found neither in edges nor parts."
)
geo_2d.lunit = lunit
return geo_2d
| from typing import Dict, List, Optional, Union
from .geo_2d_data import Geo2DData
from shapely.geometry import LineString, Polygon
def build_2d_geometry(
parts: Dict[str, List[float]],
edges: Dict[str, List[float]],
lunit: str = "nm",
build_order: Optional[List[str]] = None,
) -> Geo2DData:
"""Build a geometry in 2D.
Parameters
----------
parts : dict
Dictionary for holding the 2D parts, of the form
{'part_name':list of 2d points}.
edges : dict
Dictionary of 2D edges, of the form:
{'edge_name':list of 2d points}.
lunit : str
length_unit (nm).
(Default value = "nm")
build_order : list
None or a list of all parts, determining the build order. Items on
the left are highest priority and items on the right are lowest.
If None is given (default), then build order is determined just
taken to be the order of the parts and edges.
(Default value = None)
Returns
-------
Geo2DData instance
"""
geo_2d = Geo2DData()
if build_order is None:
build_order = list(parts)
# Set up the complete build order:
for part in parts:
if part not in build_order:
build_order.append(part)
for edge in edges:
if edge not in build_order:
build_order.append(edge)
for object_name in build_order:
if object_name in parts:
geo_2d.add_part(object_name, Polygon(parts[object_name]))
elif object_name in edges:
geo_2d.add_part(object_name, LineString(edges[object_name]))
else:
raise ValueError(
f"Object of name {object_name} was found neither in edges nor parts."
)
geo_2d.lunit = lunit
return geo_2d | en | 0.676589 | Build a geometry in 2D. Parameters ---------- parts : dict Dictionary for holding the 2D parts, of the form {'part_name':list of 2d points}. edges : dict Dictionary of 2D edges, of the form: {'edge_name':list of 2d points}. lunit : str length_unit (nm). (Default value = "nm") build_order : list None or a list of all parts, determining the build order. Items on the left are highest priority and items on the right are lowest. If None is given (default), then build order is determined just taken to be the order of the parts and edges. (Default value = None) Returns ------- Geo2DData instance # Set up the complete build order: | 2.988668 | 3 |
config.py | kaustubh-shirpurkar/wine-recommend | 0 | 6617141 | <filename>config.py
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
DEVICE = "cpu"
MAX_LEN = 128
TRAIN_BATCH_SIZE = 4
VALID_BATCH_SIZE = 4
EPOCHS = 5
NUM_LABELS = 21
BERT_PATH = "distilbert-base-uncased"
MODEL_PATH = "./model/"
TRAINING_FILE = "winemag-data-130k-v2.csv"
TOKENIZER = DistilBertTokenizer.from_pretrained(BERT_PATH, do_lower_case=True)
MODEL = DistilBertForSequenceClassification.from_pretrained(
BERT_PATH, # use 6 layer base Distil-BERT with uncased vocab
num_labels=NUM_LABELS, # Linear regression unique points
output_attentions=False, # Do not return attention weights
output_hidden_states=False ) # do not retun all hidden states | <filename>config.py
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
DEVICE = "cpu"
MAX_LEN = 128
TRAIN_BATCH_SIZE = 4
VALID_BATCH_SIZE = 4
EPOCHS = 5
NUM_LABELS = 21
BERT_PATH = "distilbert-base-uncased"
MODEL_PATH = "./model/"
TRAINING_FILE = "winemag-data-130k-v2.csv"
TOKENIZER = DistilBertTokenizer.from_pretrained(BERT_PATH, do_lower_case=True)
MODEL = DistilBertForSequenceClassification.from_pretrained(
BERT_PATH, # use 6 layer base Distil-BERT with uncased vocab
num_labels=NUM_LABELS, # Linear regression unique points
output_attentions=False, # Do not return attention weights
output_hidden_states=False ) # do not retun all hidden states | en | 0.495045 | # use 6 layer base Distil-BERT with uncased vocab # Linear regression unique points # Do not return attention weights # do not retun all hidden states | 2.166327 | 2 |
tests/test_element.py | KeironO/pyIDICk | 5 | 6617142 | <gh_stars>1-10
import unittest
import pyisopach
import numpy as np
class TestElement(unittest.TestCase):
def test_incorrect_element(self):
# Test to see if nonsense element throws an exception
self.assertRaises(KeyError, pyisopach.Element, "spooky scary skeletons", 69)
def test_molecular_weight(self):
# Check whether the calculation of molecular weight is correct.
elem = pyisopach.Element("O", 1)
self.assertAlmostEqual(elem.molecular_weight, 15.999, 3)
def test_isotopic_ratios_sum_one(self):
# Isotopic ratios should always equal 1.0, regardless of how many elements are
# passed.
elem = pyisopach.Element("O", 1)
self.assertEquals(sum(elem.isotopic_ratios), 1.0)
elem = pyisopach.Element("O", 2)
self.assertEquals(sum(elem.isotopic_ratios), 1.0)
def test_isotopic_ratios_values(self):
# Isotopic Ratios Taken from IUPAC handbook.
elem = pyisopach.Element("O", 1)
self.assertTrue(np.array_equal(elem.isotopic_ratios, [0.99757, 0.00038, 0.00205]))
def test_atomic_charge(self):
# The atomic charge of Oxygen == -2
elem = pyisopach.Element("O", 12)
self.assertEquals(elem.atomic_charge, -2)
def test_atomic_weight(self):
elem = pyisopach.Element("O", 1)
self.assertAlmostEqual(elem.atomic_weight, 15.99, 1)
def test_isotopic_weight(self):
elem = pyisopach.Element("O", 1)
self.assertAlmostEqual(sum(elem.isotopic_weight), 50.99, 1)
if __name__ == '__main__':
unittest.main() | import unittest
import pyisopach
import numpy as np
class TestElement(unittest.TestCase):
def test_incorrect_element(self):
# Test to see if nonsense element throws an exception
self.assertRaises(KeyError, pyisopach.Element, "spooky scary skeletons", 69)
def test_molecular_weight(self):
# Check whether the calculation of molecular weight is correct.
elem = pyisopach.Element("O", 1)
self.assertAlmostEqual(elem.molecular_weight, 15.999, 3)
def test_isotopic_ratios_sum_one(self):
# Isotopic ratios should always equal 1.0, regardless of how many elements are
# passed.
elem = pyisopach.Element("O", 1)
self.assertEquals(sum(elem.isotopic_ratios), 1.0)
elem = pyisopach.Element("O", 2)
self.assertEquals(sum(elem.isotopic_ratios), 1.0)
def test_isotopic_ratios_values(self):
# Isotopic Ratios Taken from IUPAC handbook.
elem = pyisopach.Element("O", 1)
self.assertTrue(np.array_equal(elem.isotopic_ratios, [0.99757, 0.00038, 0.00205]))
def test_atomic_charge(self):
# The atomic charge of Oxygen == -2
elem = pyisopach.Element("O", 12)
self.assertEquals(elem.atomic_charge, -2)
def test_atomic_weight(self):
elem = pyisopach.Element("O", 1)
self.assertAlmostEqual(elem.atomic_weight, 15.99, 1)
def test_isotopic_weight(self):
elem = pyisopach.Element("O", 1)
self.assertAlmostEqual(sum(elem.isotopic_weight), 50.99, 1)
if __name__ == '__main__':
unittest.main() | en | 0.809263 | # Test to see if nonsense element throws an exception # Check whether the calculation of molecular weight is correct. # Isotopic ratios should always equal 1.0, regardless of how many elements are # passed. # Isotopic Ratios Taken from IUPAC handbook. # The atomic charge of Oxygen == -2 | 2.87614 | 3 |
etl/io_config/epic_api.py | cloud-cds/cds-stack | 6 | 6617143 | <reponame>cloud-cds/cds-stack<filename>etl/io_config/epic_api.py
from etl.mappings.api_servers import servers
from etl.mappings.flowsheet_ids import flowsheet_ids
from etl.mappings.component_ids import component_ids
from etl.mappings.lab_procedures import lab_procedure_ids
from etl.transforms.pipelines import epic2op_transform as jhapi_transform_lists
from etl.core.environment import Environment
from etl.io_config.cloudwatch import Cloudwatch
import json
import sys
import asyncio
from aiohttp import ClientSession
from aiohttp import client_exceptions
from time import sleep
import pandas as pd
import datetime as dt
import itertools
import logging
import pytz
import random
import uvloop
from dateutil.parser import parse
from datetime import date
import traceback
import etl.io_config.core as core
import pdb
EPIC_ENV = core.get_environment_var('EPIC_ENV', '')
ALL_FLO_IDS_DICT = {}
for fid, internal_id_list in flowsheet_ids:
for internal_id in internal_id_list:
ALL_FLO_IDS_DICT[internal_id] = {'ID': str(internal_id), 'Type': 'Internal'}
ALL_FLO_IDS_LIST = list(ALL_FLO_IDS_DICT.values())
class EpicAPIConfig:
def __init__(self, lookback_hours, jhapi_server, jhapi_id,
jhapi_secret, lookback_days=None, op_lookback_days=None):
if jhapi_server not in servers:
raise ValueError("Incorrect server provided")
if int(lookback_hours) > 72:
raise ValueError("Lookback hours must be less than 72 hours")
self.jhapi_server = jhapi_server
self.server = servers[jhapi_server]
self.lookback_hours = int(lookback_hours)
self.lookback_days = int(lookback_days) if lookback_days else int(int(lookback_hours)/24.0 + 2)
self.op_lookback_days = op_lookback_days
self.from_date = (dt.datetime.now() + dt.timedelta(days=1)).strftime('%Y-%m-%d')
tomorrow = dt.datetime.now() + dt.timedelta(days=1)
self.dateFrom = (tomorrow - dt.timedelta(days=self.lookback_days)).strftime('%Y-%m-%d')
self.dateFromOneYear = (tomorrow - dt.timedelta(days=365)).strftime('%Y-%m-%d')
self.dateFromOneMonth = (tomorrow - dt.timedelta(days=30)).strftime('%Y-%m-%d')
self.dateTo = tomorrow.strftime('%Y-%m-%d')
self.headers = {
'client_id': jhapi_id,
'client_secret': jhapi_secret,
'User-Agent': ''
}
self.cloudwatch_logger = Cloudwatch()
def generate_request_settings(self, http_method, url, payloads=None, url_type=None):
request_settings = []
if isinstance(url, list):
if url_type == 'rest' and http_method == 'GET':
for u, payload in zip(url, payloads):
u = u + payload
if 'api-test' in u and EPIC_ENV:
u += ('&' if '&' in u else '?') + 'env=' + EPIC_ENV
request_settings.append({'method': http_method,'url': u})
else:
if 'api-test' in url and EPIC_ENV:
url += ('&' if '&' in url else '?') + 'env=' + EPIC_ENV
for u, payload in zip(url, payloads):
setting = {
'method': http_method,
'url': u + ('&' if '&' in u else '?') + 'env=' + EPIC_ENV if 'api-test' in u and EPIC_ENV else u
}
if payload is not None:
key = 'params' if http_method == 'GET' else 'json'
setting[key] = payload
request_settings.append(setting)
else:
if url_type == 'rest' and http_method == 'GET':
for payload in payloads:
url = url + payload
if 'api-test' in url and EPIC_ENV:
url += ('&' if '&' in url else '?') + 'env=' + EPIC_ENV
request_settings.append({'method': http_method,'url': url})
else:
if 'api-test' in url and EPIC_ENV:
url += ('&' if '&' in url else '?') + 'env=' + EPIC_ENV
for payload in payloads:
setting = {
'method': http_method,
'url': url
}
if payload is not None:
key = 'params' if http_method == 'GET' else 'json'
setting[key] = payload
request_settings.append(setting)
return request_settings
def combine(self, response_list, to_merge):
if type(response_list) != list:
raise TypeError("First argument must be a list of responses")
dfs = pd.DataFrame()
for idx, df in enumerate(response_list):
if not df.empty:
dfs = pd.concat([dfs, df.assign(index_col=idx)])
if dfs.empty:
return dfs
return pd.merge(dfs, to_merge, how='inner', left_on='index_col',
right_index=True, sort=False).drop('index_col', axis=1)
async def make_requests(self, ctxt, endpoint, payloads, http_method='GET', url_type=None, server_type='internal'):
# Define variables
server = self.server if server_type == 'internal' else servers['{}-{}'.format(self.jhapi_server, server_type)]
if isinstance(endpoint, list):
url = ["{}{}".format(server, e) for e in endpoint]
else:
url = "{}{}".format(server, endpoint)
request_settings = self.generate_request_settings(http_method, url, payloads, url_type)
semaphore = asyncio.Semaphore(ctxt.flags.JHAPI_SEMAPHORE, loop=ctxt.loop)
base = ctxt.flags.JHAPI_BACKOFF_BASE
max_backoff = ctxt.flags.JHAPI_BACKOFF_MAX
session_attempts = ctxt.flags.JHAPI_ATTEMPTS_SESSION
request_attempts = ctxt.flags.JHAPI_ATTEMPTS_REQUEST
# Asyncronous task to make a request
async def fetch(session, sem, setting):
success = 0
error = 0
for i in range(request_attempts):
try:
async with sem:
async with session.request(**setting) as response:
if response.status != 200:
body = await response.text()
logging.error("Status={}\tMessage={}\tRequest={}".format(response.status, body, setting))
response = None
error += 1
else:
response = await response.json()
success += 1
break
except IOError as e:
if i < request_attempts - 1 and e.errno in [104]: # Connection reset by peer
logging.error(e)
logging.error(setting)
traceback.print_exc()
wait_time = min(((base**i) + random.uniform(0, 1)), max_backoff)
error += 1
sleep(wait_time)
else:
raise Exception("Fail to request URL {}".format(url))
except Exception as e:
if i < request_attempts - 1 and str(e) != 'Session is closed':
logging.error(e)
logging.error(setting)
traceback.print_exc()
wait_time = min(((base**i) + random.uniform(0, 1)), max_backoff)
error += 1
sleep(wait_time)
else:
raise Exception("Fail to request URL {}".format(url))
return response, i+1, success, error
# Get the client session and create a task for each request
async def run(request_settings, semaphore, loop):
async with ClientSession(headers=self.headers, loop=loop) as session:
tasks = [asyncio.ensure_future(fetch(session, semaphore, setting),
loop=loop) for setting in request_settings]
return await asyncio.gather(*tasks)
# Start the run task to make all requests
for attempt in range(session_attempts):
try:
result = await run(request_settings, semaphore, ctxt.loop)
break
except Exception as e:
if attempt < session_attempts - 1:
logging.error("Session Error Caught for URL {}, retrying... {} times".format(url, attempt+1))
logging.exception(e)
wait_time = min(((base**attempt) + random.uniform(0, 1)), max_backoff)
sleep(wait_time)
else:
raise Exception("Session failed for URL {}".format(url))
# Push number of requests to cloudwatch
logging.info("Made {} requests".format(sum(x[1] for x in result)))
self.cloudwatch_logger.push(
dimension_name = 'ETL',
metric_name = 'requests_made_push',
value = sum(x[1] for x in result),
unit = 'Count'
)
if isinstance(endpoint, list):
labels = ['push_' + e.replace('/', '_') + '_' + http_method for e in endpoint]
for x, label in zip(result, labels):
self.cloudwatch_logger.push_many(
dimension_name = 'ETL',
metric_names = ['{}_success_push'.format(label), '{}_error_push'.format(label), 'jh_api_request_success_push', 'jh_api_request_error_push'],
metric_values = [x[2], x[3], x[2], x[3]],
metric_units = ['Count','Count','Count','Count']
)
else:
label = 'push_' + endpoint.replace('/', '_') + '_' + http_method
self.cloudwatch_logger.push_many(
dimension_name = 'ETL',
metric_names = ['{}_success_push'.format(label), '{}_error_push'.format(label), 'jh_api_request_success_push', 'jh_api_request_error_push'],
metric_values = [sum(x[2] for x in result), sum(x[3] for x in result), sum(x[2] for x in result), sum(x[3] for x in result)],
metric_units = ['Count','Count','Count','Count']
)
# Return responses
return [x[0] for x in result]
async def extract_mrn_by_zid(self, ctxt, zid):
resource = '/patients/mrn/'
payloads = [zid]
responses = await self.make_requests(ctxt, resource, payloads, 'GET', url_type='rest')
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
p = {'zid': zid}
r = responses[0]
try:
pat_id = [pid["ID"] for pid in r[0]['IDs'] if pid['Type'] == 'EMRN'][0]
except Exception as e:
logging.error("MRN Error: EID not found for zid {}".format(zid))
traceback.print_exc()
return None
sex = r[0]['Sex']
gender = 0 if sex == 'Female' else 1
try:
dob = parse(r[0]["DateOfBirth"])
age = calculate_age(dob)
except ValueError as e:
logging.warn("Unknown DOB: {}".format(zid))
age = None
p['pat_id'] = pat_id
p['age'] = age
p['gender'] = gender
return p
async def extract_ed_patients_mrn(self, ctxt, ed_patients):
resource = '/patients/mrn/'
payloads = [row['pat_id'] for i, row in ed_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET', url_type='rest')
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
for r in responses:
pat_id = [pid["ID"] for pid in r[0]['IDs'] if pid['Type'] == 'EMRN'][0]
sex = r[0]['Sex']
gender = 0 if sex == 'Female' else 1
dob = parse(r[0]["DateOfBirth"])
age = calculate_age(dob)
ed_patients.loc[ed_patients.pat_id == pat_id,'age'] = age
ed_patients.loc[ed_patients.pat_id == pat_id,'gender'] = gender
return ed_patients
async def extract_active_procedures(self, ctxt, bedded_patients, args):
bp_hospital_null = bedded_patients[bedded_patients.hospital.isnull()]
if not bp_hospital_null.empty:
logging.warn('extract_active_procedures: empty hospital: {}'.format(bp_hospital_null))
bp = bedded_patients[~bedded_patients.hospital.isnull()]
resource = ['/facilities/hospital/{}/orders/activeprocedures'.format(pat['hospital']) for _, pat in bp.iterrows()]
payloads = [{'csn': pat['visit_id']} for _, pat in bp.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
dfs = [pd.DataFrame(r) for r in responses]
df_raw = self.combine(dfs, bp[['pat_id', 'visit_id']])
return {'active_procedures_transformed': self.transform(ctxt, df_raw, 'active_procedures_transforms')}
async def extract_chiefcomplaint(self, ctxt, beddedpatients, args):
resource = '/patients/getdata/chiefcomplaint'
payloads = [{
"ContactID": {
"ID": pat['visit_id'],
"Type": "CSN"
},
"DataFormat": None,
"Items": [
{
"ItemNumber": "18100",
"LineRange": {
"From": 1,
"To": 10
}
}
],
"RecordID": {
"ID": pat['pat_id'],
"Type":"EMRN"
}
} for _, pat in beddedpatients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'POST', server_type='epic')
for r in responses:
if r:
raw_items = r['Items'][0]
new_items = '[' + ','.join(["{{\"reason\" : \"{}\"}}".format(reason) for reason in [item['Value'] for item in raw_items['Lines'] if item['LineNumber'] > 0]]) + ']'
r['Items'] = new_items
r['RecordIDs'] = None
r['ContactIDs'] = [id for id in r['ContactIDs'] if id['Type'] == 'CSN']
dfs = [pd.DataFrame(r) for r in responses]
df_raw = self.combine(dfs, beddedpatients[['pat_id', 'visit_id']])
return {'chiefcomplaint_transformed': self.transform(ctxt, df_raw, 'chiefcomplaint_transforms')}
async def extract_lab_orders(self, ctxt, bedded_patients, args):
resource = '/patients/labs/procedure'
procedure_types = []
for _, ids in lab_procedure_ids:
procedure_types += ({'Type': 'INTERNAL', 'ID': str(x)} for x in ids)
payloads = [{
'Id': pat['pat_id'],
'IdType': 'patient',
'FromDate': self.from_date,
'MaxNumberOfResults': 200,
'NumberDaysToLookBack': self.lookback_days,
'ProcedureTypes': procedure_types
} for _, pat in bedded_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'POST')
dfs = [pd.DataFrame(r['ProcedureResults'] if r else None) for r in responses]
df_raw = self.combine(dfs, bedded_patients[['pat_id', 'visit_id']])
return {'lab_orders_transformed': self.transform(ctxt, df_raw, 'lab_orders_transforms')}
async def extract_loc_history(self, ctxt, bedded_patients, args):
resource = '/patients/adtlocationhistory'
payloads = [{
'id': pat['visit_id'],
'type': 'CSN'
} for _, pat in bedded_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
dfs = [pd.DataFrame(r) for r in responses]
df_raw = self.combine(dfs, bedded_patients[['pat_id', 'visit_id']])
return {'location_history_transformed': self.transform(ctxt, df_raw, 'loc_history_transforms')}
async def extract_lab_results(self, ctxt, bedded_patients, args):
resource = '/patients/labs/component'
component_types = []
for _, cidl in component_ids:
component_types += ({'Type': 'INTERNAL', 'Value': str(x)} for x in cidl)
logging.info("extract_lab_results: {} {}".format(self.from_date, self.lookback_days))
payloads = [{
'Id': pat['pat_id'],
'IdType': 'patient',
# 'FromDate': self.from_date,
'MaxNumberOfResults': 200,
'NumberDaysToLookBack': self.lookback_days,
'ComponentTypes': component_types
} for _, pat in bedded_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'POST')
dfs = [pd.DataFrame(r['ResultComponents'] if r else None) for r in responses]
df_raw = self.combine(dfs, bedded_patients[['pat_id', 'visit_id']])
logging.info("lab results head 3: {}".format(df_raw.head(3)))
return {'lab_results_transformed': self.transform(ctxt, df_raw, 'lab_results_transforms')}
async def extract_med_admin(self, ctxt, beddedpatients, args, results):
def build_med_admin_request_data(ctxt, pats, med_orders_df, args):
if med_orders_df is None or med_orders_df.empty:
pats['ids'] = pats.apply(lambda x: [], axis=1)
else:
med_orders = med_orders_df[['pat_id', 'visit_id', 'ids']]\
.groupby(['pat_id', 'visit_id'])['ids']\
.apply(list)\
.reset_index()
pats = pd.merge(pats, med_orders, left_on=['pat_id','visit_id'], right_on=['pat_id', 'visit_id'], how='left')
for i, pt in pats.iterrows():
if (isinstance(pt['ids'], float) or len(pt['ids']) == 0) and ('med_order_ids' in args[i]):
pats.set_value(i, 'ids', [[{'ID': id, 'Type': 'Internal'}] for id in args[i]['med_order_ids']])
return pats[(pats.astype(str)['ids'] != '[]') & pats.ids.notnull()]
logging.debug("extracting med admin")
med_orders_df = None
for result in results:
for name in result:
if name == 'med_orders_transformed' and result[name] is not None:
med_orders_df = result[name]
med_orders_df['ids'] = med_orders_df['ids'].astype(list)
med_orders_df = med_orders_df[med_orders_df.order_mode == 'Inpatient']
if med_orders_df is None or med_orders_df.empty:
logging.debug("No med_orders for MAR")
return {'med_admin_transformed': None}
med_orders_df.loc[:, "ids"] = med_orders_df.ids.apply(lambda x: eval(x))
med_orders = build_med_admin_request_data(ctxt, beddedpatients, med_orders_df, args)
if med_orders is None or med_orders.empty:
logging.debug("No med_orders for MAR")
return {'med_admin_transformed': None}
else:
med_orders = med_orders.reset_index(drop=True)
resource = '/patients/medicationadministrationhistory'
payloads = [{
'ContactID': order['visit_id'],
'ContactIDType': 'CSN',
'OrderIDs': list(itertools.chain.from_iterable(order['ids'])),
'PatientID': order['pat_id']
} for _, order in med_orders.iterrows()]
logging.debug('med_orders: {}'.format(med_orders))
responses = await self.make_requests(ctxt, resource, payloads, 'POST')
dfs = [pd.DataFrame(r) for r in responses]
logging.debug('dfs: {}'.format(dfs))
df_raw = self.combine(dfs, med_orders[['pat_id', 'visit_id']])
logging.debug('df_raw: {}'.format(df_raw))
df_tran = self.transform(ctxt, df_raw, 'med_admin_transforms')
logging.debug(df_tran)
if df_tran is not None:
return {'med_admin_transformed': self.tz_hack(ctxt, df_tran)}
async def extract_med_orders(self, ctxt, bedded_patients, args):
resource = '/patients/medications'
payloads = [{
'id': pat['pat_id'],
'dayslookback': str(self.lookback_days),
'searchtype': 'IP'
} for _, pat in bedded_patients.iterrows()] + \
[{
'id': pat['pat_id'],
'dayslookback': str(self.op_lookback_days),
'searchtype': 'OP'
} for _, pat in bedded_patients.iterrows()]
self.log.debug("med_order payloads: {}".format(payloads))
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
dfs = [pd.DataFrame(r) for r in responses]
half = len(dfs)//2
med_ip = self.combine(dfs[:half], bedded_patients[['pat_id', 'visit_id']])
med_op = self.combine(dfs[half:], bedded_patients[['pat_id', 'visit_id']])
df_raw = pd.concat([med_ip, med_op]).reset_index(drop=True)
# self.log.debug("med_order df_raw: {}".format(df_raw))
if not df_raw.empty:
# self.log.debug('med_order df_raw.med-order: {}'.format(df_raw.MedicationOrders))
df_tran = self.transform(ctxt, df_raw, 'med_orders_transforms')
if df_tran is not None:
df_tran['ids'] = df_tran['ids'].astype(str)
# self.log.debug("med_order df_tran: {}".format(df_tran))
else:
self.log.debug("empty raw med_orders")
df_tran = None
return {'med_orders_transformed': df_tran}
def tz_hack(self, ctxt, df):
if not df.empty:
df['tsp'] = df['tsp'].str.replace('-04:00', '+00:00')
df['tsp'] = df['tsp'].str.replace('-05:00', '+00:00')
return df
async def extract_notes(self, ctxt, bedded_patients, args):
resource = '/patients/documents/list'
payloads = [{
'id' : pat['pat_id'],
'dateFrom' : self.dateFrom,
'dateTo' : self.dateTo
} for _, pat in bedded_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
logging.debug('#NOTES PAYLOADS: %s' % len(payloads))
logging.debug('#NOTES RESPONSES: %s' % len(responses))
dfs = [pd.DataFrame(r['DocumentListData'] if r else None) for r in responses]
df = self.combine(dfs, bedded_patients[['pat_id']])
if not df.empty:
not_empty_idx = df.Key.str.len() > 0
df = df[not_empty_idx].reset_index()
return {'notes_transformed': self.transform(ctxt, df, 'notes_transforms')}
async def extract_note_texts(self, ctxt, beddedpatients, args, results):
notes = None
for name in results:
if name == 'notes_transformed':
notes = results[name]
if notes is not None and not notes.empty:
resource = '/patients/documents/text'
payloads = [{ 'key' : note['Key'] } for _, note in notes.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
logging.debug('#NOTE TEXTS PAYLOADS: %s' % len(payloads))
logging.debug('#NOTE TEXTS RESPONSES: %s' % len(responses))
dfs = [
pd.DataFrame([{'DocumentText': r['DocumentText']}] if r else None)
for r in responses
]
df_raw = self.combine(dfs, notes[['Key']])
return {'note_texts_transformed': self.transform(ctxt, df, 'note_texts_transforms')}
return None
async def extract_flowsheets(self, ctxt, pts, args):
resource = '/patients/flowsheetrows'
payloads = [{
'ContactID': pat['visit_id'],
'ContactIDType': 'CSN',
'FlowsheetRowIDs': [ALL_FLO_IDS_DICT[id] for id in args[i]['flowsheet_ids']] if 'flowsheet_ids' in args[i] else ALL_FLO_IDS_LIST,
'LookbackHours': self.lookback_hours,
'PatientID': pat['pat_id'],
'PatientIDType': 'EMRN'
} for i, pat in pts.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'POST')
dfs = [pd.DataFrame(r) for r in responses]
df_raw = self.combine(dfs, pts[['pat_id', 'visit_id']])
if df_raw is None or df_raw.empty:
return {'flowsheets_transformed': None}
else:
df_tran = self.transform(ctxt, df_raw, 'flowsheet_transforms')
if df_tran is not None and not df_tran.empty:
return {'flowsheets_transformed': self.tz_hack(ctxt, df_tran)}
else:
return {'flowsheets_transformed': None}
async def extract_treatmentteam(self, ctxt, bedded_patients, args):
resource = '/patients/treatmentteam'
payloads = [{
'id': pat['visit_id'],
'idtype': 'csn'
} for _, pat in bedded_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
dfs = [pd.DataFrame(r['TreatmentTeam'] if r else None) for r in responses]
df_raw = self.combine(dfs, bedded_patients[['pat_id', 'visit_id']])
if df_raw is None or df_raw.empty:
return {'treatmentteam_transformed': None}
else:
df_tran = self.transform(ctxt, df_raw, 'treatmentteam_transforms')
if df_tran.empty:
return {'treatmentteam_transformed': None}
else:
return {'treatmentteam_transformed': df_tran}
async def extract_contacts(self, ctxt, pat_id_list, args, idtype='csn', dateFromOneYear=False):
def get_hospital(row):
dept = row['DepartmentName']
if dept is not None and len(dept) > 0:
if 'HC' in dept:
return 'HCGH'
elif 'JH' in dept or 'KKI' in dept:
return 'JHH'
elif 'BMC' in dept or 'BV' in dept:
return 'BMC'
elif 'SM' in dept:
return 'SMH'
elif 'SH' in dept:
return 'SH'
if not pat_id_list:
return None
resource = '/patients/contacts'
pat_id_df = pd.DataFrame(pat_id_list)
dfs = None
if idtype == 'csn':
# Get rid of fake patients by filtering out incorrect pat_ids
pat_id_df = pat_id_df[pat_id_df['pat_id'].str.contains('E.*')]
payloads = [{
'id' : pat['visit_id'],
'idtype' : 'csn',
'dateFrom' : self.dateFromOneYear if dateFromOneYear else self.dateFromOneMonth,
'dateTo' : self.dateTo,
} for _, pat in pat_id_df.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
response_dfs = [pd.DataFrame(r['Contacts'] if r else None) for r in responses]
dfs = pd.concat(response_dfs)
elif idtype == 'patient':
payloads = [{
'id' : pat['pat_id'],
'idtype' : 'patient',
'dateFrom' : self.dateFromOneYear if dateFromOneYear else self.dateFromOneMonth,
'dateTo' : self.dateTo,
} for _, pat in pat_id_df.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
response_dfs = []
logging.debug(responses)
for r in responses:
if r and r['Contacts']:
for contact in r['Contacts']:
if contact['EncounterType'] == 'Hospital Encounter' and not contact['IsCancelled']:
if not 'Outpatient' in contact['PatientClass']:
# ignore outpatient
rec = {'CSN': contact['CSN'], 'DepartmentName': contact['DepartmentName'], 'patient_class': contact['PatientClass']}
for item in r['PatientIDs']:
if item['IDType'] == 'EMRN':
rec['pat_id'] = item['ID']
logging.debug(rec)
response_dfs.append(pd.DataFrame([rec]))
dfs = pd.concat(response_dfs)
dfs['hospital'] = dfs.apply(get_hospital, axis=1)
return pd.merge(pat_id_df, dfs, left_on='pat_id', right_on='pat_id')
else:
logging.warn("No Contacts INFO for {}".format(payloads))
return None
async def extract_discharge(self, ctxt, pts, args):
if pts is None or pts.empty:
return {'discharged': None}
resource = '/patients/contacts'
# Get rid of fake patients by filtering out incorrect pat_ids
payloads = [{
'id' : pat['visit_id'],
'idtype' : 'csn',
'dateFrom' : self.dateFrom,
'dateTo' : self.dateTo,
} for _, pat in pts.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
response_dfs = [pd.DataFrame(r['Contacts'] if r else None) for r in responses]
dfs = pd.concat(response_dfs)
if dfs.empty:
return {'discharged': None}
else:
contacts = pd.merge(pts, dfs, left_on='visit_id', right_on='CSN')
discharged = await self.create_discharge_times(ctxt, contacts)
return {'discharged': discharged}
async def create_discharge_times(self, ctxt, contacts_df):
if contacts_df.empty:
return
discharged_df = contacts_df[contacts_df['DischargeDate'] != '']
if discharged_df.empty:
return None
def build_value(row):
value = json.dumps({
'disposition': row['DischargeDisposition'],
'department': row['DepartmentName']
})
return value
discharged_df['confidence'] = 1
discharged_df['fid'] = 'discharge'
discharged_df['tsp'] = discharged_df['DischargeDate']
discharged_df['value'] = discharged_df.apply(build_value, axis=1)
return discharged_df
def skip_none(self, df, transform_function):
if df is None or df.empty:
return None
try:
start = dt.datetime.now()
df = transform_function(df)
logging.debug("function time: {}".format(dt.datetime.now() - start))
return df
except Exception as e:
logging.error("== EXCEPTION CAUGHT ==")
logging.error("reason for error: " + e.reason)
logging.error(e.context)
traceback.print_exc()
def transform(self, ctxt, df, transform_list_name):
if df is None:
return None
if type(df) == list:
df = pd.concat(df)
for transform_fn in getattr(jhapi_transform_lists, transform_list_name):
df = self.skip_none(df, transform_fn)
return df | from etl.mappings.api_servers import servers
from etl.mappings.flowsheet_ids import flowsheet_ids
from etl.mappings.component_ids import component_ids
from etl.mappings.lab_procedures import lab_procedure_ids
from etl.transforms.pipelines import epic2op_transform as jhapi_transform_lists
from etl.core.environment import Environment
from etl.io_config.cloudwatch import Cloudwatch
import json
import sys
import asyncio
from aiohttp import ClientSession
from aiohttp import client_exceptions
from time import sleep
import pandas as pd
import datetime as dt
import itertools
import logging
import pytz
import random
import uvloop
from dateutil.parser import parse
from datetime import date
import traceback
import etl.io_config.core as core
import pdb
EPIC_ENV = core.get_environment_var('EPIC_ENV', '')
ALL_FLO_IDS_DICT = {}
for fid, internal_id_list in flowsheet_ids:
for internal_id in internal_id_list:
ALL_FLO_IDS_DICT[internal_id] = {'ID': str(internal_id), 'Type': 'Internal'}
ALL_FLO_IDS_LIST = list(ALL_FLO_IDS_DICT.values())
class EpicAPIConfig:
def __init__(self, lookback_hours, jhapi_server, jhapi_id,
jhapi_secret, lookback_days=None, op_lookback_days=None):
if jhapi_server not in servers:
raise ValueError("Incorrect server provided")
if int(lookback_hours) > 72:
raise ValueError("Lookback hours must be less than 72 hours")
self.jhapi_server = jhapi_server
self.server = servers[jhapi_server]
self.lookback_hours = int(lookback_hours)
self.lookback_days = int(lookback_days) if lookback_days else int(int(lookback_hours)/24.0 + 2)
self.op_lookback_days = op_lookback_days
self.from_date = (dt.datetime.now() + dt.timedelta(days=1)).strftime('%Y-%m-%d')
tomorrow = dt.datetime.now() + dt.timedelta(days=1)
self.dateFrom = (tomorrow - dt.timedelta(days=self.lookback_days)).strftime('%Y-%m-%d')
self.dateFromOneYear = (tomorrow - dt.timedelta(days=365)).strftime('%Y-%m-%d')
self.dateFromOneMonth = (tomorrow - dt.timedelta(days=30)).strftime('%Y-%m-%d')
self.dateTo = tomorrow.strftime('%Y-%m-%d')
self.headers = {
'client_id': jhapi_id,
'client_secret': jhapi_secret,
'User-Agent': ''
}
self.cloudwatch_logger = Cloudwatch()
def generate_request_settings(self, http_method, url, payloads=None, url_type=None):
request_settings = []
if isinstance(url, list):
if url_type == 'rest' and http_method == 'GET':
for u, payload in zip(url, payloads):
u = u + payload
if 'api-test' in u and EPIC_ENV:
u += ('&' if '&' in u else '?') + 'env=' + EPIC_ENV
request_settings.append({'method': http_method,'url': u})
else:
if 'api-test' in url and EPIC_ENV:
url += ('&' if '&' in url else '?') + 'env=' + EPIC_ENV
for u, payload in zip(url, payloads):
setting = {
'method': http_method,
'url': u + ('&' if '&' in u else '?') + 'env=' + EPIC_ENV if 'api-test' in u and EPIC_ENV else u
}
if payload is not None:
key = 'params' if http_method == 'GET' else 'json'
setting[key] = payload
request_settings.append(setting)
else:
if url_type == 'rest' and http_method == 'GET':
for payload in payloads:
url = url + payload
if 'api-test' in url and EPIC_ENV:
url += ('&' if '&' in url else '?') + 'env=' + EPIC_ENV
request_settings.append({'method': http_method,'url': url})
else:
if 'api-test' in url and EPIC_ENV:
url += ('&' if '&' in url else '?') + 'env=' + EPIC_ENV
for payload in payloads:
setting = {
'method': http_method,
'url': url
}
if payload is not None:
key = 'params' if http_method == 'GET' else 'json'
setting[key] = payload
request_settings.append(setting)
return request_settings
def combine(self, response_list, to_merge):
if type(response_list) != list:
raise TypeError("First argument must be a list of responses")
dfs = pd.DataFrame()
for idx, df in enumerate(response_list):
if not df.empty:
dfs = pd.concat([dfs, df.assign(index_col=idx)])
if dfs.empty:
return dfs
return pd.merge(dfs, to_merge, how='inner', left_on='index_col',
right_index=True, sort=False).drop('index_col', axis=1)
async def make_requests(self, ctxt, endpoint, payloads, http_method='GET', url_type=None, server_type='internal'):
# Define variables
server = self.server if server_type == 'internal' else servers['{}-{}'.format(self.jhapi_server, server_type)]
if isinstance(endpoint, list):
url = ["{}{}".format(server, e) for e in endpoint]
else:
url = "{}{}".format(server, endpoint)
request_settings = self.generate_request_settings(http_method, url, payloads, url_type)
semaphore = asyncio.Semaphore(ctxt.flags.JHAPI_SEMAPHORE, loop=ctxt.loop)
base = ctxt.flags.JHAPI_BACKOFF_BASE
max_backoff = ctxt.flags.JHAPI_BACKOFF_MAX
session_attempts = ctxt.flags.JHAPI_ATTEMPTS_SESSION
request_attempts = ctxt.flags.JHAPI_ATTEMPTS_REQUEST
# Asyncronous task to make a request
async def fetch(session, sem, setting):
success = 0
error = 0
for i in range(request_attempts):
try:
async with sem:
async with session.request(**setting) as response:
if response.status != 200:
body = await response.text()
logging.error("Status={}\tMessage={}\tRequest={}".format(response.status, body, setting))
response = None
error += 1
else:
response = await response.json()
success += 1
break
except IOError as e:
if i < request_attempts - 1 and e.errno in [104]: # Connection reset by peer
logging.error(e)
logging.error(setting)
traceback.print_exc()
wait_time = min(((base**i) + random.uniform(0, 1)), max_backoff)
error += 1
sleep(wait_time)
else:
raise Exception("Fail to request URL {}".format(url))
except Exception as e:
if i < request_attempts - 1 and str(e) != 'Session is closed':
logging.error(e)
logging.error(setting)
traceback.print_exc()
wait_time = min(((base**i) + random.uniform(0, 1)), max_backoff)
error += 1
sleep(wait_time)
else:
raise Exception("Fail to request URL {}".format(url))
return response, i+1, success, error
# Get the client session and create a task for each request
async def run(request_settings, semaphore, loop):
async with ClientSession(headers=self.headers, loop=loop) as session:
tasks = [asyncio.ensure_future(fetch(session, semaphore, setting),
loop=loop) for setting in request_settings]
return await asyncio.gather(*tasks)
# Start the run task to make all requests
for attempt in range(session_attempts):
try:
result = await run(request_settings, semaphore, ctxt.loop)
break
except Exception as e:
if attempt < session_attempts - 1:
logging.error("Session Error Caught for URL {}, retrying... {} times".format(url, attempt+1))
logging.exception(e)
wait_time = min(((base**attempt) + random.uniform(0, 1)), max_backoff)
sleep(wait_time)
else:
raise Exception("Session failed for URL {}".format(url))
# Push number of requests to cloudwatch
logging.info("Made {} requests".format(sum(x[1] for x in result)))
self.cloudwatch_logger.push(
dimension_name = 'ETL',
metric_name = 'requests_made_push',
value = sum(x[1] for x in result),
unit = 'Count'
)
if isinstance(endpoint, list):
labels = ['push_' + e.replace('/', '_') + '_' + http_method for e in endpoint]
for x, label in zip(result, labels):
self.cloudwatch_logger.push_many(
dimension_name = 'ETL',
metric_names = ['{}_success_push'.format(label), '{}_error_push'.format(label), 'jh_api_request_success_push', 'jh_api_request_error_push'],
metric_values = [x[2], x[3], x[2], x[3]],
metric_units = ['Count','Count','Count','Count']
)
else:
label = 'push_' + endpoint.replace('/', '_') + '_' + http_method
self.cloudwatch_logger.push_many(
dimension_name = 'ETL',
metric_names = ['{}_success_push'.format(label), '{}_error_push'.format(label), 'jh_api_request_success_push', 'jh_api_request_error_push'],
metric_values = [sum(x[2] for x in result), sum(x[3] for x in result), sum(x[2] for x in result), sum(x[3] for x in result)],
metric_units = ['Count','Count','Count','Count']
)
# Return responses
return [x[0] for x in result]
async def extract_mrn_by_zid(self, ctxt, zid):
resource = '/patients/mrn/'
payloads = [zid]
responses = await self.make_requests(ctxt, resource, payloads, 'GET', url_type='rest')
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
p = {'zid': zid}
r = responses[0]
try:
pat_id = [pid["ID"] for pid in r[0]['IDs'] if pid['Type'] == 'EMRN'][0]
except Exception as e:
logging.error("MRN Error: EID not found for zid {}".format(zid))
traceback.print_exc()
return None
sex = r[0]['Sex']
gender = 0 if sex == 'Female' else 1
try:
dob = parse(r[0]["DateOfBirth"])
age = calculate_age(dob)
except ValueError as e:
logging.warn("Unknown DOB: {}".format(zid))
age = None
p['pat_id'] = pat_id
p['age'] = age
p['gender'] = gender
return p
async def extract_ed_patients_mrn(self, ctxt, ed_patients):
resource = '/patients/mrn/'
payloads = [row['pat_id'] for i, row in ed_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET', url_type='rest')
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
for r in responses:
pat_id = [pid["ID"] for pid in r[0]['IDs'] if pid['Type'] == 'EMRN'][0]
sex = r[0]['Sex']
gender = 0 if sex == 'Female' else 1
dob = parse(r[0]["DateOfBirth"])
age = calculate_age(dob)
ed_patients.loc[ed_patients.pat_id == pat_id,'age'] = age
ed_patients.loc[ed_patients.pat_id == pat_id,'gender'] = gender
return ed_patients
async def extract_active_procedures(self, ctxt, bedded_patients, args):
bp_hospital_null = bedded_patients[bedded_patients.hospital.isnull()]
if not bp_hospital_null.empty:
logging.warn('extract_active_procedures: empty hospital: {}'.format(bp_hospital_null))
bp = bedded_patients[~bedded_patients.hospital.isnull()]
resource = ['/facilities/hospital/{}/orders/activeprocedures'.format(pat['hospital']) for _, pat in bp.iterrows()]
payloads = [{'csn': pat['visit_id']} for _, pat in bp.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
dfs = [pd.DataFrame(r) for r in responses]
df_raw = self.combine(dfs, bp[['pat_id', 'visit_id']])
return {'active_procedures_transformed': self.transform(ctxt, df_raw, 'active_procedures_transforms')}
async def extract_chiefcomplaint(self, ctxt, beddedpatients, args):
resource = '/patients/getdata/chiefcomplaint'
payloads = [{
"ContactID": {
"ID": pat['visit_id'],
"Type": "CSN"
},
"DataFormat": None,
"Items": [
{
"ItemNumber": "18100",
"LineRange": {
"From": 1,
"To": 10
}
}
],
"RecordID": {
"ID": pat['pat_id'],
"Type":"EMRN"
}
} for _, pat in beddedpatients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'POST', server_type='epic')
for r in responses:
if r:
raw_items = r['Items'][0]
new_items = '[' + ','.join(["{{\"reason\" : \"{}\"}}".format(reason) for reason in [item['Value'] for item in raw_items['Lines'] if item['LineNumber'] > 0]]) + ']'
r['Items'] = new_items
r['RecordIDs'] = None
r['ContactIDs'] = [id for id in r['ContactIDs'] if id['Type'] == 'CSN']
dfs = [pd.DataFrame(r) for r in responses]
df_raw = self.combine(dfs, beddedpatients[['pat_id', 'visit_id']])
return {'chiefcomplaint_transformed': self.transform(ctxt, df_raw, 'chiefcomplaint_transforms')}
async def extract_lab_orders(self, ctxt, bedded_patients, args):
resource = '/patients/labs/procedure'
procedure_types = []
for _, ids in lab_procedure_ids:
procedure_types += ({'Type': 'INTERNAL', 'ID': str(x)} for x in ids)
payloads = [{
'Id': pat['pat_id'],
'IdType': 'patient',
'FromDate': self.from_date,
'MaxNumberOfResults': 200,
'NumberDaysToLookBack': self.lookback_days,
'ProcedureTypes': procedure_types
} for _, pat in bedded_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'POST')
dfs = [pd.DataFrame(r['ProcedureResults'] if r else None) for r in responses]
df_raw = self.combine(dfs, bedded_patients[['pat_id', 'visit_id']])
return {'lab_orders_transformed': self.transform(ctxt, df_raw, 'lab_orders_transforms')}
async def extract_loc_history(self, ctxt, bedded_patients, args):
resource = '/patients/adtlocationhistory'
payloads = [{
'id': pat['visit_id'],
'type': 'CSN'
} for _, pat in bedded_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
dfs = [pd.DataFrame(r) for r in responses]
df_raw = self.combine(dfs, bedded_patients[['pat_id', 'visit_id']])
return {'location_history_transformed': self.transform(ctxt, df_raw, 'loc_history_transforms')}
async def extract_lab_results(self, ctxt, bedded_patients, args):
resource = '/patients/labs/component'
component_types = []
for _, cidl in component_ids:
component_types += ({'Type': 'INTERNAL', 'Value': str(x)} for x in cidl)
logging.info("extract_lab_results: {} {}".format(self.from_date, self.lookback_days))
payloads = [{
'Id': pat['pat_id'],
'IdType': 'patient',
# 'FromDate': self.from_date,
'MaxNumberOfResults': 200,
'NumberDaysToLookBack': self.lookback_days,
'ComponentTypes': component_types
} for _, pat in bedded_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'POST')
dfs = [pd.DataFrame(r['ResultComponents'] if r else None) for r in responses]
df_raw = self.combine(dfs, bedded_patients[['pat_id', 'visit_id']])
logging.info("lab results head 3: {}".format(df_raw.head(3)))
return {'lab_results_transformed': self.transform(ctxt, df_raw, 'lab_results_transforms')}
async def extract_med_admin(self, ctxt, beddedpatients, args, results):
def build_med_admin_request_data(ctxt, pats, med_orders_df, args):
if med_orders_df is None or med_orders_df.empty:
pats['ids'] = pats.apply(lambda x: [], axis=1)
else:
med_orders = med_orders_df[['pat_id', 'visit_id', 'ids']]\
.groupby(['pat_id', 'visit_id'])['ids']\
.apply(list)\
.reset_index()
pats = pd.merge(pats, med_orders, left_on=['pat_id','visit_id'], right_on=['pat_id', 'visit_id'], how='left')
for i, pt in pats.iterrows():
if (isinstance(pt['ids'], float) or len(pt['ids']) == 0) and ('med_order_ids' in args[i]):
pats.set_value(i, 'ids', [[{'ID': id, 'Type': 'Internal'}] for id in args[i]['med_order_ids']])
return pats[(pats.astype(str)['ids'] != '[]') & pats.ids.notnull()]
logging.debug("extracting med admin")
med_orders_df = None
for result in results:
for name in result:
if name == 'med_orders_transformed' and result[name] is not None:
med_orders_df = result[name]
med_orders_df['ids'] = med_orders_df['ids'].astype(list)
med_orders_df = med_orders_df[med_orders_df.order_mode == 'Inpatient']
if med_orders_df is None or med_orders_df.empty:
logging.debug("No med_orders for MAR")
return {'med_admin_transformed': None}
med_orders_df.loc[:, "ids"] = med_orders_df.ids.apply(lambda x: eval(x))
med_orders = build_med_admin_request_data(ctxt, beddedpatients, med_orders_df, args)
if med_orders is None or med_orders.empty:
logging.debug("No med_orders for MAR")
return {'med_admin_transformed': None}
else:
med_orders = med_orders.reset_index(drop=True)
resource = '/patients/medicationadministrationhistory'
payloads = [{
'ContactID': order['visit_id'],
'ContactIDType': 'CSN',
'OrderIDs': list(itertools.chain.from_iterable(order['ids'])),
'PatientID': order['pat_id']
} for _, order in med_orders.iterrows()]
logging.debug('med_orders: {}'.format(med_orders))
responses = await self.make_requests(ctxt, resource, payloads, 'POST')
dfs = [pd.DataFrame(r) for r in responses]
logging.debug('dfs: {}'.format(dfs))
df_raw = self.combine(dfs, med_orders[['pat_id', 'visit_id']])
logging.debug('df_raw: {}'.format(df_raw))
df_tran = self.transform(ctxt, df_raw, 'med_admin_transforms')
logging.debug(df_tran)
if df_tran is not None:
return {'med_admin_transformed': self.tz_hack(ctxt, df_tran)}
async def extract_med_orders(self, ctxt, bedded_patients, args):
resource = '/patients/medications'
payloads = [{
'id': pat['pat_id'],
'dayslookback': str(self.lookback_days),
'searchtype': 'IP'
} for _, pat in bedded_patients.iterrows()] + \
[{
'id': pat['pat_id'],
'dayslookback': str(self.op_lookback_days),
'searchtype': 'OP'
} for _, pat in bedded_patients.iterrows()]
self.log.debug("med_order payloads: {}".format(payloads))
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
dfs = [pd.DataFrame(r) for r in responses]
half = len(dfs)//2
med_ip = self.combine(dfs[:half], bedded_patients[['pat_id', 'visit_id']])
med_op = self.combine(dfs[half:], bedded_patients[['pat_id', 'visit_id']])
df_raw = pd.concat([med_ip, med_op]).reset_index(drop=True)
# self.log.debug("med_order df_raw: {}".format(df_raw))
if not df_raw.empty:
# self.log.debug('med_order df_raw.med-order: {}'.format(df_raw.MedicationOrders))
df_tran = self.transform(ctxt, df_raw, 'med_orders_transforms')
if df_tran is not None:
df_tran['ids'] = df_tran['ids'].astype(str)
# self.log.debug("med_order df_tran: {}".format(df_tran))
else:
self.log.debug("empty raw med_orders")
df_tran = None
return {'med_orders_transformed': df_tran}
def tz_hack(self, ctxt, df):
if not df.empty:
df['tsp'] = df['tsp'].str.replace('-04:00', '+00:00')
df['tsp'] = df['tsp'].str.replace('-05:00', '+00:00')
return df
async def extract_notes(self, ctxt, bedded_patients, args):
resource = '/patients/documents/list'
payloads = [{
'id' : pat['pat_id'],
'dateFrom' : self.dateFrom,
'dateTo' : self.dateTo
} for _, pat in bedded_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
logging.debug('#NOTES PAYLOADS: %s' % len(payloads))
logging.debug('#NOTES RESPONSES: %s' % len(responses))
dfs = [pd.DataFrame(r['DocumentListData'] if r else None) for r in responses]
df = self.combine(dfs, bedded_patients[['pat_id']])
if not df.empty:
not_empty_idx = df.Key.str.len() > 0
df = df[not_empty_idx].reset_index()
return {'notes_transformed': self.transform(ctxt, df, 'notes_transforms')}
async def extract_note_texts(self, ctxt, beddedpatients, args, results):
notes = None
for name in results:
if name == 'notes_transformed':
notes = results[name]
if notes is not None and not notes.empty:
resource = '/patients/documents/text'
payloads = [{ 'key' : note['Key'] } for _, note in notes.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
logging.debug('#NOTE TEXTS PAYLOADS: %s' % len(payloads))
logging.debug('#NOTE TEXTS RESPONSES: %s' % len(responses))
dfs = [
pd.DataFrame([{'DocumentText': r['DocumentText']}] if r else None)
for r in responses
]
df_raw = self.combine(dfs, notes[['Key']])
return {'note_texts_transformed': self.transform(ctxt, df, 'note_texts_transforms')}
return None
async def extract_flowsheets(self, ctxt, pts, args):
resource = '/patients/flowsheetrows'
payloads = [{
'ContactID': pat['visit_id'],
'ContactIDType': 'CSN',
'FlowsheetRowIDs': [ALL_FLO_IDS_DICT[id] for id in args[i]['flowsheet_ids']] if 'flowsheet_ids' in args[i] else ALL_FLO_IDS_LIST,
'LookbackHours': self.lookback_hours,
'PatientID': pat['pat_id'],
'PatientIDType': 'EMRN'
} for i, pat in pts.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'POST')
dfs = [pd.DataFrame(r) for r in responses]
df_raw = self.combine(dfs, pts[['pat_id', 'visit_id']])
if df_raw is None or df_raw.empty:
return {'flowsheets_transformed': None}
else:
df_tran = self.transform(ctxt, df_raw, 'flowsheet_transforms')
if df_tran is not None and not df_tran.empty:
return {'flowsheets_transformed': self.tz_hack(ctxt, df_tran)}
else:
return {'flowsheets_transformed': None}
async def extract_treatmentteam(self, ctxt, bedded_patients, args):
resource = '/patients/treatmentteam'
payloads = [{
'id': pat['visit_id'],
'idtype': 'csn'
} for _, pat in bedded_patients.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
dfs = [pd.DataFrame(r['TreatmentTeam'] if r else None) for r in responses]
df_raw = self.combine(dfs, bedded_patients[['pat_id', 'visit_id']])
if df_raw is None or df_raw.empty:
return {'treatmentteam_transformed': None}
else:
df_tran = self.transform(ctxt, df_raw, 'treatmentteam_transforms')
if df_tran.empty:
return {'treatmentteam_transformed': None}
else:
return {'treatmentteam_transformed': df_tran}
async def extract_contacts(self, ctxt, pat_id_list, args, idtype='csn', dateFromOneYear=False):
def get_hospital(row):
dept = row['DepartmentName']
if dept is not None and len(dept) > 0:
if 'HC' in dept:
return 'HCGH'
elif 'JH' in dept or 'KKI' in dept:
return 'JHH'
elif 'BMC' in dept or 'BV' in dept:
return 'BMC'
elif 'SM' in dept:
return 'SMH'
elif 'SH' in dept:
return 'SH'
if not pat_id_list:
return None
resource = '/patients/contacts'
pat_id_df = pd.DataFrame(pat_id_list)
dfs = None
if idtype == 'csn':
# Get rid of fake patients by filtering out incorrect pat_ids
pat_id_df = pat_id_df[pat_id_df['pat_id'].str.contains('E.*')]
payloads = [{
'id' : pat['visit_id'],
'idtype' : 'csn',
'dateFrom' : self.dateFromOneYear if dateFromOneYear else self.dateFromOneMonth,
'dateTo' : self.dateTo,
} for _, pat in pat_id_df.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
response_dfs = [pd.DataFrame(r['Contacts'] if r else None) for r in responses]
dfs = pd.concat(response_dfs)
elif idtype == 'patient':
payloads = [{
'id' : pat['pat_id'],
'idtype' : 'patient',
'dateFrom' : self.dateFromOneYear if dateFromOneYear else self.dateFromOneMonth,
'dateTo' : self.dateTo,
} for _, pat in pat_id_df.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
response_dfs = []
logging.debug(responses)
for r in responses:
if r and r['Contacts']:
for contact in r['Contacts']:
if contact['EncounterType'] == 'Hospital Encounter' and not contact['IsCancelled']:
if not 'Outpatient' in contact['PatientClass']:
# ignore outpatient
rec = {'CSN': contact['CSN'], 'DepartmentName': contact['DepartmentName'], 'patient_class': contact['PatientClass']}
for item in r['PatientIDs']:
if item['IDType'] == 'EMRN':
rec['pat_id'] = item['ID']
logging.debug(rec)
response_dfs.append(pd.DataFrame([rec]))
dfs = pd.concat(response_dfs)
dfs['hospital'] = dfs.apply(get_hospital, axis=1)
return pd.merge(pat_id_df, dfs, left_on='pat_id', right_on='pat_id')
else:
logging.warn("No Contacts INFO for {}".format(payloads))
return None
async def extract_discharge(self, ctxt, pts, args):
if pts is None or pts.empty:
return {'discharged': None}
resource = '/patients/contacts'
# Get rid of fake patients by filtering out incorrect pat_ids
payloads = [{
'id' : pat['visit_id'],
'idtype' : 'csn',
'dateFrom' : self.dateFrom,
'dateTo' : self.dateTo,
} for _, pat in pts.iterrows()]
responses = await self.make_requests(ctxt, resource, payloads, 'GET')
response_dfs = [pd.DataFrame(r['Contacts'] if r else None) for r in responses]
dfs = pd.concat(response_dfs)
if dfs.empty:
return {'discharged': None}
else:
contacts = pd.merge(pts, dfs, left_on='visit_id', right_on='CSN')
discharged = await self.create_discharge_times(ctxt, contacts)
return {'discharged': discharged}
async def create_discharge_times(self, ctxt, contacts_df):
if contacts_df.empty:
return
discharged_df = contacts_df[contacts_df['DischargeDate'] != '']
if discharged_df.empty:
return None
def build_value(row):
value = json.dumps({
'disposition': row['DischargeDisposition'],
'department': row['DepartmentName']
})
return value
discharged_df['confidence'] = 1
discharged_df['fid'] = 'discharge'
discharged_df['tsp'] = discharged_df['DischargeDate']
discharged_df['value'] = discharged_df.apply(build_value, axis=1)
return discharged_df
def skip_none(self, df, transform_function):
if df is None or df.empty:
return None
try:
start = dt.datetime.now()
df = transform_function(df)
logging.debug("function time: {}".format(dt.datetime.now() - start))
return df
except Exception as e:
logging.error("== EXCEPTION CAUGHT ==")
logging.error("reason for error: " + e.reason)
logging.error(e.context)
traceback.print_exc()
def transform(self, ctxt, df, transform_list_name):
if df is None:
return None
if type(df) == list:
df = pd.concat(df)
for transform_fn in getattr(jhapi_transform_lists, transform_list_name):
df = self.skip_none(df, transform_fn)
return df | en | 0.578649 | # Define variables # Asyncronous task to make a request # Connection reset by peer # Get the client session and create a task for each request # Start the run task to make all requests # Push number of requests to cloudwatch # Return responses # 'FromDate': self.from_date, # self.log.debug("med_order df_raw: {}".format(df_raw)) # self.log.debug('med_order df_raw.med-order: {}'.format(df_raw.MedicationOrders)) # self.log.debug("med_order df_tran: {}".format(df_tran)) # Get rid of fake patients by filtering out incorrect pat_ids # ignore outpatient # Get rid of fake patients by filtering out incorrect pat_ids | 1.995416 | 2 |
src/apps/staples/api/models.py | columbia/fairtest | 42 | 6617144 | <filename>src/apps/staples/api/models.py
from django.db import models
class User(models.Model):
RACE_CHOICES = (\
(1, 'White Not Hispanic or Latino'),
(2, 'Hispanic or Latino'),
(3, 'Black or African American'),
(4, 'American Indian and Alaska Native'),
(5, 'Asian'),
(6, 'Native Hawaiian and Other Pacific Islander'),
(7, 'Some Other Race'),
(8, 'Two or More Races'),)
SEX_CHOICES = (\
(0, 'M'),
(1, 'F'),)
INCOME_CHOICES = (\
(1, 'income<5000'),
(2, '5000<=income<10000'),
(3, '10000<=income<20000'),
(4, '20000<=income<50000'),
(5, '50000<=income<80000'),
(6, '80000<=income<160000'),
(7, '160000<=income<320000'),
(8, '320000<=income'),)
uid = models.IntegerField(primary_key=True)
zipcode = models.CharField(max_length=10)
city = models.CharField(max_length=60)
state = models.CharField(max_length=30)
sex = models.IntegerField(choices=SEX_CHOICES)
race = models.IntegerField(choices=RACE_CHOICES)
income = models.IntegerField(choices=INCOME_CHOICES)
def __str__(self):
return str(self.uid)
def get_attribute(self, attribute):
if attribute == "sex":
return str(self.sex)
elif attribute == "income":
return str(self.income)
elif attribute == "race":
return str(self.race)
else:
return ""
class Store(models.Model):
zipcode = models.CharField(primary_key=True, max_length=10)
latitude = models.FloatField()
longitude = models.FloatField()
class Competitor(models.Model):
zipcode = models.CharField(primary_key=True, max_length=10)
latitude = models.FloatField()
longitude = models.FloatField()
class Zipcode(models.Model):
zipcode = models.CharField(primary_key=True, max_length=10)
latitude = models.FloatField()
longitude = models.FloatField()
| <filename>src/apps/staples/api/models.py
from django.db import models
class User(models.Model):
RACE_CHOICES = (\
(1, 'White Not Hispanic or Latino'),
(2, 'Hispanic or Latino'),
(3, 'Black or African American'),
(4, 'American Indian and Alaska Native'),
(5, 'Asian'),
(6, 'Native Hawaiian and Other Pacific Islander'),
(7, 'Some Other Race'),
(8, 'Two or More Races'),)
SEX_CHOICES = (\
(0, 'M'),
(1, 'F'),)
INCOME_CHOICES = (\
(1, 'income<5000'),
(2, '5000<=income<10000'),
(3, '10000<=income<20000'),
(4, '20000<=income<50000'),
(5, '50000<=income<80000'),
(6, '80000<=income<160000'),
(7, '160000<=income<320000'),
(8, '320000<=income'),)
uid = models.IntegerField(primary_key=True)
zipcode = models.CharField(max_length=10)
city = models.CharField(max_length=60)
state = models.CharField(max_length=30)
sex = models.IntegerField(choices=SEX_CHOICES)
race = models.IntegerField(choices=RACE_CHOICES)
income = models.IntegerField(choices=INCOME_CHOICES)
def __str__(self):
return str(self.uid)
def get_attribute(self, attribute):
if attribute == "sex":
return str(self.sex)
elif attribute == "income":
return str(self.income)
elif attribute == "race":
return str(self.race)
else:
return ""
class Store(models.Model):
zipcode = models.CharField(primary_key=True, max_length=10)
latitude = models.FloatField()
longitude = models.FloatField()
class Competitor(models.Model):
zipcode = models.CharField(primary_key=True, max_length=10)
latitude = models.FloatField()
longitude = models.FloatField()
class Zipcode(models.Model):
zipcode = models.CharField(primary_key=True, max_length=10)
latitude = models.FloatField()
longitude = models.FloatField()
| none | 1 | 2.748246 | 3 | |
Problem_56/main.py | jdalzatec/EulerProject | 1 | 6617145 | max_sum = 0
for a in range(100):
for b in range(100):
suma = sum(int(i) for i in str(a ** b))
if suma > max_sum:
max_sum = suma
print(max_sum)
# time 0.162 s | max_sum = 0
for a in range(100):
for b in range(100):
suma = sum(int(i) for i in str(a ** b))
if suma > max_sum:
max_sum = suma
print(max_sum)
# time 0.162 s | eu | 0.425639 | # time 0.162 s | 3.451491 | 3 |
results.py | scooter-dangle/MStream | 69 | 6617146 | <reponame>scooter-dangle/MStream<gh_stars>10-100
from sklearn import metrics
import pandas as pd
import numpy as np
import argparse
parser = argparse.ArgumentParser(description="Find AUC")
parser.add_argument("--label", help="labels file", required=True)
parser.add_argument("--scores", help="scores file", required=True)
args = parser.parse_args()
data = pd.read_csv(args.label, names=["label"])
is_anom = data.label
scores = pd.read_csv(args.scores, header=None, squeeze=True)
fpr, tpr, _ = metrics.roc_curve(is_anom, scores)
auc = metrics.roc_auc_score(is_anom, scores)
count = np.sum(is_anom)
preds = np.zeros_like(is_anom)
indices = np.argsort(scores, axis=0)[::-1]
preds[indices[:count]] = 1
print(
"AUC: ", auc,
)
| from sklearn import metrics
import pandas as pd
import numpy as np
import argparse
parser = argparse.ArgumentParser(description="Find AUC")
parser.add_argument("--label", help="labels file", required=True)
parser.add_argument("--scores", help="scores file", required=True)
args = parser.parse_args()
data = pd.read_csv(args.label, names=["label"])
is_anom = data.label
scores = pd.read_csv(args.scores, header=None, squeeze=True)
fpr, tpr, _ = metrics.roc_curve(is_anom, scores)
auc = metrics.roc_auc_score(is_anom, scores)
count = np.sum(is_anom)
preds = np.zeros_like(is_anom)
indices = np.argsort(scores, axis=0)[::-1]
preds[indices[:count]] = 1
print(
"AUC: ", auc,
) | none | 1 | 2.554618 | 3 | |
stacks/XIAOMATECH/1.0/services/KYLIN/package/scripts/kylin.py | tvorogme/dataops | 3 | 6617147 | <gh_stars>1-10
import glob
import os
from resource_management.core.resources import Directory
from resource_management.core.resources.system import Execute, File
from resource_management.core.source import InlineTemplate, StaticFile
from resource_management.core.logger import Logger
from resource_management.libraries.functions.check_process_status import check_process_status
from resource_management.libraries.functions.format import format
from resource_management.libraries.script.script import Script
from resource_management.libraries import XmlConfig
def install_kylin():
import params
if not os.path.exists(Script.get_stack_root() + '/' + params.version_dir) or not os.path.exists(
params.install_dir):
Execute('rm -rf %s' % Script.get_stack_root() + '/' + params.version_dir)
Execute('rm -rf %s' % params.install_dir)
Execute(
'wget ' + params.download_url + ' -O /tmp/' + params.filename,
user=params.kylin_user)
Execute('tar -zxf /tmp/' + params.filename + ' -C ' + Script.get_stack_root())
Execute('ln -s ' + Script.get_stack_root() + '/' + params.version_dir + ' ' + params.install_dir)
Execute(' mkdir -p ' + params.conf_dir + ' && cp -r ' +
params.install_dir + '/conf/* ' + params.conf_dir)
Execute(' rm -rf ' + params.install_dir + '/conf')
Execute('ln -s ' + params.conf_dir + ' ' + params.install_dir +
'/conf')
Execute(' rm -rf ' + params.install_dir + '/logs')
Execute('ln -s ' + params.kylin_log_dir + ' ' + params.install_dir +
'/logs')
Execute("echo 'export PATH=%s/bin:$PATH'>/etc/profile.d/kylin.sh" %
params.install_dir)
Execute('chown -R %s:%s %s/%s' %
(params.kylin_user, params.kylin_group,params.stack_root, params.version_dir))
Execute('chown -R %s:%s %s' % (params.kylin_user, params.kylin_group,
params.install_dir))
Execute('/bin/rm -f /tmp/' + params.filename)
class Job(Script):
def install(self, env):
import params
env.set_params(params)
install_kylin()
self.create_kylin_dir()
Execute('ln -s ' + params.install_dir + '/pid ' +
params.kylin_pid_file)
Directory([
params.kylin_pid_dir, params.kylin_dir, params.conf_dir,
params.kylin_log_dir
],
owner=params.kylin_user,
group=params.kylin_group,
cd_access="a",
create_parents=True,
mode=0755)
File(
params.conf_dir + '/kylin-env.sh',
mode=0755,
content=InlineTemplate(params.kylin_env_template),
owner=params.kylin_user,
group=params.kylin_group)
File(
params.conf_dir + '/SCSinkTools.json',
mode=755,
content=StaticFile('SCSinkTools.json'))
File(
params.conf_dir + '/system_cube.sh',
mode=755,
content=StaticFile('system_cube.sh'))
Execute('source ' + params.conf_dir + '/kylin-env.sh; ' +
params.conf_dir + '/system_cube.sh')
def create_kylin_dir(self):
import params
params.HdfsResource(
format("/user/{kylin_user}"),
type="directory",
action="create_on_execute",
owner=params.kylin_user,
group=params.kylin_group,
recursive_chown=True,
recursive_chmod=True)
params.HdfsResource(
format("/logs/spark/kylin"),
type="directory",
action="create_on_execute",
owner=params.kylin_user,
group=params.kylin_group,
recursive_chown=True,
recursive_chmod=True)
params.HdfsResource(
format("/kylin"),
type="directory",
action="create_on_execute",
owner=params.kylin_user,
group=params.kylin_group,
recursive_chown=True,
recursive_chmod=True)
params.HdfsResource(None, action="execute")
def configure(self, env):
import params
env.set_params(params)
File(
os.path.join(params.conf_dir, "kylin.properties"),
content=InlineTemplate(params.kylin_properties_template),
owner=params.kylin_user,
group=params.kylin_group)
XmlConfig(
"kylin_hive_conf.xml",
conf_dir=params.conf_dir,
configurations=params.config['configurations']['kylin_hive_conf'],
owner=params.kylin_user,
group=params.kylin_group)
XmlConfig(
"kylin_job_conf.xml",
conf_dir=params.conf_dir,
configurations=params.config['configurations']['kylin_job_conf'],
owner=params.kylin_user,
group=params.kylin_group)
XmlConfig(
"kylin_job_conf_inmem.xml",
conf_dir=params.conf_dir,
configurations=params.config['configurations']
['kylin_job_conf_inmem'],
owner=params.kylin_user,
group=params.kylin_group)
XmlConfig(
"kylin-kafka-consumer.xml",
conf_dir=params.conf_dir,
configurations=params.config['configurations']
['kylin-kafka-consumer'],
owner=params.kylin_user,
group=params.kylin_group)
File(
os.path.join(params.conf_dir, "kylin-server-log4j.properties"),
mode=0644,
group=params.kylin_group,
owner=params.kylin_user,
content=InlineTemplate(params.log4j_server_props))
File(
os.path.join(params.conf_dir, "kylin-tools-log4j.properties"),
mode=0644,
group=params.kylin_group,
owner=params.kylin_user,
content=InlineTemplate(params.log4j_tool_props))
def stop(self, env):
import params
Execute(
params.kylin_dir + '/bin/kylin.sh stop >> ' +
params.kylin_log_file,
user=params.kylin_user)
def start(self, env):
import params
install_kylin()
self.configure(env)
if params.security_enabled:
kylin_kinit_cmd = format(
"{kinit_path_local} -kt {kylin_kerberos_keytab} {kylin_kerberos_principal}; "
)
Execute(kylin_kinit_cmd, user=params.kylin_user)
Execute(
' source ' + params.conf_dir + '/kylin-env.sh ;' + params.kylin_dir
+ '/bin/kylin.sh start >> ' + params.kylin_log_file,
user=params.kylin_user)
pidfile = params.kylin_pid_file
Logger.info(format("Pid file is: {pidfile}"))
def status(self, env):
import status_params
env.set_params(status_params)
check_process_status(status_params.kylin_pid_file)
def get_pid_files(self):
import params
return [params.kylin_pid_file]
if __name__ == "__main__":
Job().execute()
| import glob
import os
from resource_management.core.resources import Directory
from resource_management.core.resources.system import Execute, File
from resource_management.core.source import InlineTemplate, StaticFile
from resource_management.core.logger import Logger
from resource_management.libraries.functions.check_process_status import check_process_status
from resource_management.libraries.functions.format import format
from resource_management.libraries.script.script import Script
from resource_management.libraries import XmlConfig
def install_kylin():
import params
if not os.path.exists(Script.get_stack_root() + '/' + params.version_dir) or not os.path.exists(
params.install_dir):
Execute('rm -rf %s' % Script.get_stack_root() + '/' + params.version_dir)
Execute('rm -rf %s' % params.install_dir)
Execute(
'wget ' + params.download_url + ' -O /tmp/' + params.filename,
user=params.kylin_user)
Execute('tar -zxf /tmp/' + params.filename + ' -C ' + Script.get_stack_root())
Execute('ln -s ' + Script.get_stack_root() + '/' + params.version_dir + ' ' + params.install_dir)
Execute(' mkdir -p ' + params.conf_dir + ' && cp -r ' +
params.install_dir + '/conf/* ' + params.conf_dir)
Execute(' rm -rf ' + params.install_dir + '/conf')
Execute('ln -s ' + params.conf_dir + ' ' + params.install_dir +
'/conf')
Execute(' rm -rf ' + params.install_dir + '/logs')
Execute('ln -s ' + params.kylin_log_dir + ' ' + params.install_dir +
'/logs')
Execute("echo 'export PATH=%s/bin:$PATH'>/etc/profile.d/kylin.sh" %
params.install_dir)
Execute('chown -R %s:%s %s/%s' %
(params.kylin_user, params.kylin_group,params.stack_root, params.version_dir))
Execute('chown -R %s:%s %s' % (params.kylin_user, params.kylin_group,
params.install_dir))
Execute('/bin/rm -f /tmp/' + params.filename)
class Job(Script):
def install(self, env):
import params
env.set_params(params)
install_kylin()
self.create_kylin_dir()
Execute('ln -s ' + params.install_dir + '/pid ' +
params.kylin_pid_file)
Directory([
params.kylin_pid_dir, params.kylin_dir, params.conf_dir,
params.kylin_log_dir
],
owner=params.kylin_user,
group=params.kylin_group,
cd_access="a",
create_parents=True,
mode=0755)
File(
params.conf_dir + '/kylin-env.sh',
mode=0755,
content=InlineTemplate(params.kylin_env_template),
owner=params.kylin_user,
group=params.kylin_group)
File(
params.conf_dir + '/SCSinkTools.json',
mode=755,
content=StaticFile('SCSinkTools.json'))
File(
params.conf_dir + '/system_cube.sh',
mode=755,
content=StaticFile('system_cube.sh'))
Execute('source ' + params.conf_dir + '/kylin-env.sh; ' +
params.conf_dir + '/system_cube.sh')
def create_kylin_dir(self):
import params
params.HdfsResource(
format("/user/{kylin_user}"),
type="directory",
action="create_on_execute",
owner=params.kylin_user,
group=params.kylin_group,
recursive_chown=True,
recursive_chmod=True)
params.HdfsResource(
format("/logs/spark/kylin"),
type="directory",
action="create_on_execute",
owner=params.kylin_user,
group=params.kylin_group,
recursive_chown=True,
recursive_chmod=True)
params.HdfsResource(
format("/kylin"),
type="directory",
action="create_on_execute",
owner=params.kylin_user,
group=params.kylin_group,
recursive_chown=True,
recursive_chmod=True)
params.HdfsResource(None, action="execute")
def configure(self, env):
import params
env.set_params(params)
File(
os.path.join(params.conf_dir, "kylin.properties"),
content=InlineTemplate(params.kylin_properties_template),
owner=params.kylin_user,
group=params.kylin_group)
XmlConfig(
"kylin_hive_conf.xml",
conf_dir=params.conf_dir,
configurations=params.config['configurations']['kylin_hive_conf'],
owner=params.kylin_user,
group=params.kylin_group)
XmlConfig(
"kylin_job_conf.xml",
conf_dir=params.conf_dir,
configurations=params.config['configurations']['kylin_job_conf'],
owner=params.kylin_user,
group=params.kylin_group)
XmlConfig(
"kylin_job_conf_inmem.xml",
conf_dir=params.conf_dir,
configurations=params.config['configurations']
['kylin_job_conf_inmem'],
owner=params.kylin_user,
group=params.kylin_group)
XmlConfig(
"kylin-kafka-consumer.xml",
conf_dir=params.conf_dir,
configurations=params.config['configurations']
['kylin-kafka-consumer'],
owner=params.kylin_user,
group=params.kylin_group)
File(
os.path.join(params.conf_dir, "kylin-server-log4j.properties"),
mode=0644,
group=params.kylin_group,
owner=params.kylin_user,
content=InlineTemplate(params.log4j_server_props))
File(
os.path.join(params.conf_dir, "kylin-tools-log4j.properties"),
mode=0644,
group=params.kylin_group,
owner=params.kylin_user,
content=InlineTemplate(params.log4j_tool_props))
def stop(self, env):
import params
Execute(
params.kylin_dir + '/bin/kylin.sh stop >> ' +
params.kylin_log_file,
user=params.kylin_user)
def start(self, env):
import params
install_kylin()
self.configure(env)
if params.security_enabled:
kylin_kinit_cmd = format(
"{kinit_path_local} -kt {kylin_kerberos_keytab} {kylin_kerberos_principal}; "
)
Execute(kylin_kinit_cmd, user=params.kylin_user)
Execute(
' source ' + params.conf_dir + '/kylin-env.sh ;' + params.kylin_dir
+ '/bin/kylin.sh start >> ' + params.kylin_log_file,
user=params.kylin_user)
pidfile = params.kylin_pid_file
Logger.info(format("Pid file is: {pidfile}"))
def status(self, env):
import status_params
env.set_params(status_params)
check_process_status(status_params.kylin_pid_file)
def get_pid_files(self):
import params
return [params.kylin_pid_file]
if __name__ == "__main__":
Job().execute() | none | 1 | 1.903417 | 2 | |
setup.py | hwfan/DriveDownloader | 26 | 6617148 | from setuptools import setup, find_packages
setup(
name = "DriveDownloader",
version = "1.3.0",
keywords = ("drivedownloader", "drive", "netdrive", "download"),
description = "A Python netdrive downloader.",
long_description = "A Python netdrive downloader.",
license = "MIT Licence",
url = "https://hwfan.io",
author = "hwfan",
author_email = "<EMAIL>",
packages = find_packages(),
include_package_data = True,
platforms = "any",
install_requires = ['argparse', 'requests', 'tqdm', 'pysocks'],
scripts = [],
entry_points = {
'console_scripts': [
'ddl = DriveDownloader.downloader:simple_cli'
]
}
)
| from setuptools import setup, find_packages
setup(
name = "DriveDownloader",
version = "1.3.0",
keywords = ("drivedownloader", "drive", "netdrive", "download"),
description = "A Python netdrive downloader.",
long_description = "A Python netdrive downloader.",
license = "MIT Licence",
url = "https://hwfan.io",
author = "hwfan",
author_email = "<EMAIL>",
packages = find_packages(),
include_package_data = True,
platforms = "any",
install_requires = ['argparse', 'requests', 'tqdm', 'pysocks'],
scripts = [],
entry_points = {
'console_scripts': [
'ddl = DriveDownloader.downloader:simple_cli'
]
}
)
| none | 1 | 1.575309 | 2 | |
__init__.py | genba2/pinybotbeta-enhanced | 0 | 6617149 | """
pinylib (originally called tinylib) provides an easy way to interface with tinychat chat rooms.
It contains classes/methods and functions to establish a connection
to tinychat's RTMP server. The idea was to make a library/module that would serve
as a building block for developers, wanting to make a helper and/or entertainment bot.
"""
__author__ = 'nortxort'
__copyright__ = 'Copyright 2017, nortxort'
__credits__ = ['MegaLoler', 'GoelBiju', 'notnola', 'prekageo', 'Anorov', 'hydralabs']
__license__ = 'MIT'
| """
pinylib (originally called tinylib) provides an easy way to interface with tinychat chat rooms.
It contains classes/methods and functions to establish a connection
to tinychat's RTMP server. The idea was to make a library/module that would serve
as a building block for developers, wanting to make a helper and/or entertainment bot.
"""
__author__ = 'nortxort'
__copyright__ = 'Copyright 2017, nortxort'
__credits__ = ['MegaLoler', 'GoelBiju', 'notnola', 'prekageo', 'Anorov', 'hydralabs']
__license__ = 'MIT'
| en | 0.952855 | pinylib (originally called tinylib) provides an easy way to interface with tinychat chat rooms. It contains classes/methods and functions to establish a connection to tinychat's RTMP server. The idea was to make a library/module that would serve as a building block for developers, wanting to make a helper and/or entertainment bot. | 1.47009 | 1 |
multi_feature_clip_raster.py | danzelenak-usgs/ArcPy_Tools | 0 | 6617150 | <filename>multi_feature_clip_raster.py<gh_stars>0
"""
Use a shapefile with multiple features to clip a raster or multiple rasters. The script will process all rasters in
the specified input directory.
****Requires the ArcGIS python interpreter****
"""
import os
import arcpy
import argparse
import datetime as dt
from arcpy import env
def get_time():
"""
Return the current time
:return:
"""
return dt.datetime.now()
def get_raster(raster_list, y):
"""
Ensure we pull the appropriate raster for the given year and don't assume a 1:1 relationship
between items in raster_list and years.
:param raster_list:
:param y:
:return:
"""
raster = [r for r in raster_list if str(y) in r]
if len(raster) > 0:
# Here I'm assuming:
# 1. that each file will contain a unique year, and
# 2. there is only 1 year in the filename
return raster[-1]
else:
return None
def main_work(indir, outdir, shp, out_prod, field="id", years=None):
"""
:param indir:
:param outdir:
:param shp:
:param out_prod:
:param field:
:param years:
:return:
"""
env.workspace = indir
env.compression = "NONE"
split_shape = shp
in_rasters = arcpy.ListRasters()
split_field = field
if years is None:
years = range(1984, 2016)
cursor = arcpy.SearchCursor(split_shape)
for row in cursor:
current_val = row.getValue(split_field)
subdir = outdir + os.sep + "block_%s" % current_val
if not os.path.exists(subdir):
os.makedirs(subdir)
for year in years:
in_rast = get_raster(in_rasters, year)
if in_rast is None:
print("Could not find matching raster for year %s" % year)
continue
result_name = "%s%s%s_block_%s_%s.tif" % (subdir, os.sep, out_prod, current_val, year)
if os.path.exists(result_name):
continue
# Create feature layer of current clipping polygon
where_clause = "%s = %s" % (split_field, current_val)
arcpy.MakeFeatureLayer_management(split_shape, 'currentMask', where_clause)
arcpy.AddMessage("Processing: " + result_name)
# Save the clipped raster
arcpy.Clip_management(
in_rast,
rectangle="#",
out_raster=result_name,
in_template_dataset='currentMask',
nodata_value="255",
clipping_geometry="ClippingGeometry",
maintain_clipping_extent="MAINTAIN_EXTENT"
)
if arcpy.Exists('currentMask'):
arcpy.Delete_management('currentMask')
return None
def main():
"""
:return:
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-i", dest="indir", required=True, type=str,
help="The full path to the input directory that will be used as the Workspace Environment.")
parser.add_argument("-o", dest="outdir", required=True, type=str,
help="The full path to the output directory")
parser.add_argument("-shp", dest="shp", required=True, type=str,
help="The full path to the clipping shapefile")
parser.add_argument("-f", "--field", dest="field", required=True, type=str,
help="The name of the attribute field used to identify the splitting features")
parser.add_argument("-y", "--years", dest="years", required=False, type=str, nargs="*",
help="Optionally specify the target years.")
parser.add_argument("-n", "--name", dest="out_prod", required=True, type=str,
help="Specify the name of the product (e.g. Trends, CoverPrim, etc.)")
args = parser.parse_args()
main_work(**vars(args))
return None
if __name__ == "__main__":
t1 = get_time()
main()
t2 = get_time()
print("Processing Time: %s " % str(t2 - t1))
| <filename>multi_feature_clip_raster.py<gh_stars>0
"""
Use a shapefile with multiple features to clip a raster or multiple rasters. The script will process all rasters in
the specified input directory.
****Requires the ArcGIS python interpreter****
"""
import os
import arcpy
import argparse
import datetime as dt
from arcpy import env
def get_time():
"""
Return the current time
:return:
"""
return dt.datetime.now()
def get_raster(raster_list, y):
"""
Ensure we pull the appropriate raster for the given year and don't assume a 1:1 relationship
between items in raster_list and years.
:param raster_list:
:param y:
:return:
"""
raster = [r for r in raster_list if str(y) in r]
if len(raster) > 0:
# Here I'm assuming:
# 1. that each file will contain a unique year, and
# 2. there is only 1 year in the filename
return raster[-1]
else:
return None
def main_work(indir, outdir, shp, out_prod, field="id", years=None):
"""
:param indir:
:param outdir:
:param shp:
:param out_prod:
:param field:
:param years:
:return:
"""
env.workspace = indir
env.compression = "NONE"
split_shape = shp
in_rasters = arcpy.ListRasters()
split_field = field
if years is None:
years = range(1984, 2016)
cursor = arcpy.SearchCursor(split_shape)
for row in cursor:
current_val = row.getValue(split_field)
subdir = outdir + os.sep + "block_%s" % current_val
if not os.path.exists(subdir):
os.makedirs(subdir)
for year in years:
in_rast = get_raster(in_rasters, year)
if in_rast is None:
print("Could not find matching raster for year %s" % year)
continue
result_name = "%s%s%s_block_%s_%s.tif" % (subdir, os.sep, out_prod, current_val, year)
if os.path.exists(result_name):
continue
# Create feature layer of current clipping polygon
where_clause = "%s = %s" % (split_field, current_val)
arcpy.MakeFeatureLayer_management(split_shape, 'currentMask', where_clause)
arcpy.AddMessage("Processing: " + result_name)
# Save the clipped raster
arcpy.Clip_management(
in_rast,
rectangle="#",
out_raster=result_name,
in_template_dataset='currentMask',
nodata_value="255",
clipping_geometry="ClippingGeometry",
maintain_clipping_extent="MAINTAIN_EXTENT"
)
if arcpy.Exists('currentMask'):
arcpy.Delete_management('currentMask')
return None
def main():
"""
:return:
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-i", dest="indir", required=True, type=str,
help="The full path to the input directory that will be used as the Workspace Environment.")
parser.add_argument("-o", dest="outdir", required=True, type=str,
help="The full path to the output directory")
parser.add_argument("-shp", dest="shp", required=True, type=str,
help="The full path to the clipping shapefile")
parser.add_argument("-f", "--field", dest="field", required=True, type=str,
help="The name of the attribute field used to identify the splitting features")
parser.add_argument("-y", "--years", dest="years", required=False, type=str, nargs="*",
help="Optionally specify the target years.")
parser.add_argument("-n", "--name", dest="out_prod", required=True, type=str,
help="Specify the name of the product (e.g. Trends, CoverPrim, etc.)")
args = parser.parse_args()
main_work(**vars(args))
return None
if __name__ == "__main__":
t1 = get_time()
main()
t2 = get_time()
print("Processing Time: %s " % str(t2 - t1))
| en | 0.751339 | Use a shapefile with multiple features to clip a raster or multiple rasters. The script will process all rasters in
the specified input directory.
****Requires the ArcGIS python interpreter**** Return the current time
:return: Ensure we pull the appropriate raster for the given year and don't assume a 1:1 relationship
between items in raster_list and years.
:param raster_list:
:param y:
:return: # Here I'm assuming: # 1. that each file will contain a unique year, and # 2. there is only 1 year in the filename :param indir:
:param outdir:
:param shp:
:param out_prod:
:param field:
:param years:
:return: # Create feature layer of current clipping polygon # Save the clipped raster :return: | 2.986626 | 3 |