body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
7a6de3c556c2a2afbb81a8cf3b78e78332457333e424c2365845fb79390ff891 | def _setChecked(self, parm):
"Check / Uncheck all checkers for a given category.\n\n This method is called by the Houdini node when a 'Load all' checkbox\n is checked / unchecked.\n\n Parameter\n ---------\n parm: hou.Parm\n The parm which has been checked / unchecked.\... | Check / Uncheck all checkers for a given category.
This method is called by the Houdini node when a 'Load all' checkbox
is checked / unchecked.
Parameter
---------
parm: hou.Parm
The parm which has been checked / unchecked. | scripts/houdini/DigitalAssets/ZefirReader/View.py | _setChecked | RadicalTeapot/nwave | 0 | python | def _setChecked(self, parm):
"Check / Uncheck all checkers for a given category.\n\n This method is called by the Houdini node when a 'Load all' checkbox\n is checked / unchecked.\n\n Parameter\n ---------\n parm: hou.Parm\n The parm which has been checked / unchecked.\... | def _setChecked(self, parm):
"Check / Uncheck all checkers for a given category.\n\n This method is called by the Houdini node when a 'Load all' checkbox\n is checked / unchecked.\n\n Parameter\n ---------\n parm: hou.Parm\n The parm which has been checked / unchecked.\... |
c7560ad2003c3ffa830ed35ea0a7cf796460bfb30d7499c4e73ea13321c8a1eb | def _seqShotChanged(self):
"Sequence or shot number has been modified by user.\n\n This method is called by the Houdini node when the 'sequenceshot' parm\n is modified by the user.\n "
self.seqShotChanged() | Sequence or shot number has been modified by user.
This method is called by the Houdini node when the 'sequenceshot' parm
is modified by the user. | scripts/houdini/DigitalAssets/ZefirReader/View.py | _seqShotChanged | RadicalTeapot/nwave | 0 | python | def _seqShotChanged(self):
"Sequence or shot number has been modified by user.\n\n This method is called by the Houdini node when the 'sequenceshot' parm\n is modified by the user.\n "
self.seqShotChanged() | def _seqShotChanged(self):
"Sequence or shot number has been modified by user.\n\n This method is called by the Houdini node when the 'sequenceshot' parm\n is modified by the user.\n "
self.seqShotChanged()<|docstring|>Sequence or shot number has been modified by user.
This method is calle... |
746803a4761d787befb2322f4d52bcfecd7353068d598043693d434bd14abfa0 | def _loadAssetChecked(self, parm):
'Load parm has been checked / unchecked.\n\n This method is called by the Houdini node when an asset load checkbox\n state has changed.\n\n Parameter\n ---------\n parm: hou.Parm\n The parm which has been checked / unchecked.\n\n ... | Load parm has been checked / unchecked.
This method is called by the Houdini node when an asset load checkbox
state has changed.
Parameter
---------
parm: hou.Parm
The parm which has been checked / unchecked. | scripts/houdini/DigitalAssets/ZefirReader/View.py | _loadAssetChecked | RadicalTeapot/nwave | 0 | python | def _loadAssetChecked(self, parm):
'Load parm has been checked / unchecked.\n\n This method is called by the Houdini node when an asset load checkbox\n state has changed.\n\n Parameter\n ---------\n parm: hou.Parm\n The parm which has been checked / unchecked.\n\n ... | def _loadAssetChecked(self, parm):
'Load parm has been checked / unchecked.\n\n This method is called by the Houdini node when an asset load checkbox\n state has changed.\n\n Parameter\n ---------\n parm: hou.Parm\n The parm which has been checked / unchecked.\n\n ... |
ec88b485a5b5b9ff697b7fcee94f8273072d44e083944247794ca1230c71fbbc | def _assetNameChanged(self, parm):
'Asset name has been modified by user.\n\n This method is called by the Houdini node when an asset name has been\n changed by the user\n\n Parameter\n ---------\n parm: hou.Parm\n The asset name parm.\n\n '
self.assetNameCha... | Asset name has been modified by user.
This method is called by the Houdini node when an asset name has been
changed by the user
Parameter
---------
parm: hou.Parm
The asset name parm. | scripts/houdini/DigitalAssets/ZefirReader/View.py | _assetNameChanged | RadicalTeapot/nwave | 0 | python | def _assetNameChanged(self, parm):
'Asset name has been modified by user.\n\n This method is called by the Houdini node when an asset name has been\n changed by the user\n\n Parameter\n ---------\n parm: hou.Parm\n The asset name parm.\n\n '
self.assetNameCha... | def _assetNameChanged(self, parm):
'Asset name has been modified by user.\n\n This method is called by the Houdini node when an asset name has been\n changed by the user\n\n Parameter\n ---------\n parm: hou.Parm\n The asset name parm.\n\n '
self.assetNameCha... |
8637049c0ad14db5fc8164550b3f57f115c788eafecc3a0a285566b922aa0787 | def _assetStageChanged(self, parm):
'Asset stage has been changed by the user.\n\n This method is called by the Houdini node when an asset stage to load\n has been changed by the user.\n\n Parameter\n ---------\n parm: hou.Parm\n The stage menu parm.\n\n '
se... | Asset stage has been changed by the user.
This method is called by the Houdini node when an asset stage to load
has been changed by the user.
Parameter
---------
parm: hou.Parm
The stage menu parm. | scripts/houdini/DigitalAssets/ZefirReader/View.py | _assetStageChanged | RadicalTeapot/nwave | 0 | python | def _assetStageChanged(self, parm):
'Asset stage has been changed by the user.\n\n This method is called by the Houdini node when an asset stage to load\n has been changed by the user.\n\n Parameter\n ---------\n parm: hou.Parm\n The stage menu parm.\n\n '
se... | def _assetStageChanged(self, parm):
'Asset stage has been changed by the user.\n\n This method is called by the Houdini node when an asset stage to load\n has been changed by the user.\n\n Parameter\n ---------\n parm: hou.Parm\n The stage menu parm.\n\n '
se... |
ac9cb551156716bee7229e7b8a5cfe9658035cceea839b4b88e5b4f6a06e3e15 | def _getParm(self, template, category, parm_id=None):
'Find and return a parm with given category and id.\n\n Parameters\n ----------\n template: str\n The parm name template.\n category: str\n The category of the parm to find.\n parm_id: str or int\n ... | Find and return a parm with given category and id.
Parameters
----------
template: str
The parm name template.
category: str
The category of the parm to find.
parm_id: str or int
The id of the parm to find.
Raises
------
RuntimeError
If a parm with the given category and id cannot be found.
Returns
-... | scripts/houdini/DigitalAssets/ZefirReader/View.py | _getParm | RadicalTeapot/nwave | 0 | python | def _getParm(self, template, category, parm_id=None):
'Find and return a parm with given category and id.\n\n Parameters\n ----------\n template: str\n The parm name template.\n category: str\n The category of the parm to find.\n parm_id: str or int\n ... | def _getParm(self, template, category, parm_id=None):
'Find and return a parm with given category and id.\n\n Parameters\n ----------\n template: str\n The parm name template.\n category: str\n The category of the parm to find.\n parm_id: str or int\n ... |
1895dac1c783602f2872f7956ae9794b2171e4e9dba3f2025a6ba7938f4ea816 | @property
def sequence(self):
'int: the number of the sequence to load.'
return self._node.parm('sequenceshotx').evalAsInt() | int: the number of the sequence to load. | scripts/houdini/DigitalAssets/ZefirReader/View.py | sequence | RadicalTeapot/nwave | 0 | python | @property
def sequence(self):
return self._node.parm('sequenceshotx').evalAsInt() | @property
def sequence(self):
return self._node.parm('sequenceshotx').evalAsInt()<|docstring|>int: the number of the sequence to load.<|endoftext|> |
3c1927d07bb97060b1a8c12735ba99b9745bd6b58395b62c0a2ec80e28899beb | @property
def shot(self):
'int: the number of the shot to load.'
return self._node.parm('sequenceshoty').evalAsInt() | int: the number of the shot to load. | scripts/houdini/DigitalAssets/ZefirReader/View.py | shot | RadicalTeapot/nwave | 0 | python | @property
def shot(self):
return self._node.parm('sequenceshoty').evalAsInt() | @property
def shot(self):
return self._node.parm('sequenceshoty').evalAsInt()<|docstring|>int: the number of the shot to load.<|endoftext|> |
f6243cf09efe020faeab5643ea01f98f21df6a4754c77ec459007dbc67808015 | def getAssetCount(self, category):
'Return the asset count for the given category.\n\n Parameter\n ----------\n category: str\n The name of the asset category.\n\n Returns\n -------\n int\n The number of assets for the given category.\n\n '
... | Return the asset count for the given category.
Parameter
----------
category: str
The name of the asset category.
Returns
-------
int
The number of assets for the given category. | scripts/houdini/DigitalAssets/ZefirReader/View.py | getAssetCount | RadicalTeapot/nwave | 0 | python | def getAssetCount(self, category):
'Return the asset count for the given category.\n\n Parameter\n ----------\n category: str\n The name of the asset category.\n\n Returns\n -------\n int\n The number of assets for the given category.\n\n '
... | def getAssetCount(self, category):
'Return the asset count for the given category.\n\n Parameter\n ----------\n category: str\n The name of the asset category.\n\n Returns\n -------\n int\n The number of assets for the given category.\n\n '
... |
0abcee86fce4aab3ddf3eb7585e44b737bffc0a8f65792b8105c1d15cabe1c58 | def setAssetCount(self, category, count):
'Set the asset count for a given category.\n\n Parameters\n ----------\n category: str\n The name of the category for which to set the asset count.\n count: int\n The value to use for the asset count.\n\n '
self._... | Set the asset count for a given category.
Parameters
----------
category: str
The name of the category for which to set the asset count.
count: int
The value to use for the asset count. | scripts/houdini/DigitalAssets/ZefirReader/View.py | setAssetCount | RadicalTeapot/nwave | 0 | python | def setAssetCount(self, category, count):
'Set the asset count for a given category.\n\n Parameters\n ----------\n category: str\n The name of the category for which to set the asset count.\n count: int\n The value to use for the asset count.\n\n '
self._... | def setAssetCount(self, category, count):
'Set the asset count for a given category.\n\n Parameters\n ----------\n category: str\n The name of the category for which to set the asset count.\n count: int\n The value to use for the asset count.\n\n '
self._... |
d40b098daa12a93280b74a5723b355229f6d977a3f4908ebc55e574d824ebef7 | def getLoadAsset(self, category, parm_id):
'Return the state of a load asset with given category and parm id.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to get.\n\n Returns\n ... | Return the state of a load asset with given category and parm id.
Parameters
----------
category: str
The name of the category the asset belongs to.
parm_id: int
The id of parm to get.
Returns
-------
bool
The state of the load asset checkbox. | scripts/houdini/DigitalAssets/ZefirReader/View.py | getLoadAsset | RadicalTeapot/nwave | 0 | python | def getLoadAsset(self, category, parm_id):
'Return the state of a load asset with given category and parm id.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to get.\n\n Returns\n ... | def getLoadAsset(self, category, parm_id):
'Return the state of a load asset with given category and parm id.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to get.\n\n Returns\n ... |
d2cf79ec285cff050db23fa1dfc56e2011d666af75d259b6b9a13bbd2eabe203 | def setLoadAsset(self, category, parm_id, value):
'Set the checkbox state to load an asset.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to change.\n value: bool\n The ... | Set the checkbox state to load an asset.
Parameters
----------
category: str
The name of the category the asset belongs to.
parm_id: int
The id of parm to change.
value: bool
The state to set the checkbox. | scripts/houdini/DigitalAssets/ZefirReader/View.py | setLoadAsset | RadicalTeapot/nwave | 0 | python | def setLoadAsset(self, category, parm_id, value):
'Set the checkbox state to load an asset.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to change.\n value: bool\n The ... | def setLoadAsset(self, category, parm_id, value):
'Set the checkbox state to load an asset.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to change.\n value: bool\n The ... |
3638e0bdba460976c6905f2a569007c9f46135b648c338f073b0ba63a328c108 | def getLoadAll(self, category):
'Return the state of the load all checkbox for given category.\n\n Parameters\n ----------\n category: str\n The name of the category.\n\n Returns\n -------\n bool\n The state of the load all checkbox.\n\n '
s... | Return the state of the load all checkbox for given category.
Parameters
----------
category: str
The name of the category.
Returns
-------
bool
The state of the load all checkbox. | scripts/houdini/DigitalAssets/ZefirReader/View.py | getLoadAll | RadicalTeapot/nwave | 0 | python | def getLoadAll(self, category):
'Return the state of the load all checkbox for given category.\n\n Parameters\n ----------\n category: str\n The name of the category.\n\n Returns\n -------\n bool\n The state of the load all checkbox.\n\n '
s... | def getLoadAll(self, category):
'Return the state of the load all checkbox for given category.\n\n Parameters\n ----------\n category: str\n The name of the category.\n\n Returns\n -------\n bool\n The state of the load all checkbox.\n\n '
s... |
4165f2b1739eef4dfe5cbd3bcfa5190f24aba42dd4b90a3dd468939d386d47a8 | def setLoadAll(self, category, value):
'Set the checkbox state to load all assets of given category.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n value: bool\n The state to set the checkbox.\n\n '
if (not ... | Set the checkbox state to load all assets of given category.
Parameters
----------
category: str
The name of the category the asset belongs to.
value: bool
The state to set the checkbox. | scripts/houdini/DigitalAssets/ZefirReader/View.py | setLoadAll | RadicalTeapot/nwave | 0 | python | def setLoadAll(self, category, value):
'Set the checkbox state to load all assets of given category.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n value: bool\n The state to set the checkbox.\n\n '
if (not ... | def setLoadAll(self, category, value):
'Set the checkbox state to load all assets of given category.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n value: bool\n The state to set the checkbox.\n\n '
if (not ... |
d7843ba0aacf6dec02a902b3f6ca79d3cf4b0dadc80934a2940d351706b0b5be | def getAssetName(self, category, parm_id):
'Return the name for the asset with given category and parm id.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to get.\n\n Returns\n ... | Return the name for the asset with given category and parm id.
Parameters
----------
category: str
The name of the category the asset belongs to.
parm_id: int
The id of parm to get.
Returns
-------
str
The name for the asset. | scripts/houdini/DigitalAssets/ZefirReader/View.py | getAssetName | RadicalTeapot/nwave | 0 | python | def getAssetName(self, category, parm_id):
'Return the name for the asset with given category and parm id.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to get.\n\n Returns\n ... | def getAssetName(self, category, parm_id):
'Return the name for the asset with given category and parm id.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to get.\n\n Returns\n ... |
511e4397dfe4deef75147a325524aa56aac93a9a9a8001c96edac8b6675c1b81 | def setAssetName(self, category, parm_id, value):
'Set the name for the asset with given category and parm id.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to change.\n value: boo... | Set the name for the asset with given category and parm id.
Parameters
----------
category: str
The name of the category the asset belongs to.
parm_id: int
The id of parm to change.
value: bool
The state to set the checkbox. | scripts/houdini/DigitalAssets/ZefirReader/View.py | setAssetName | RadicalTeapot/nwave | 0 | python | def setAssetName(self, category, parm_id, value):
'Set the name for the asset with given category and parm id.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to change.\n value: boo... | def setAssetName(self, category, parm_id, value):
'Set the name for the asset with given category and parm id.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to change.\n value: boo... |
6bd14a6ef0a12b237119ec0ca76b681c6153e92616b4a777b27ea2423555a4e3 | def getAssetStage(self, category, parm_id):
'Return the stage if of the stage to load for an asset.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to get.\n\n Returns\n -----... | Return the stage if of the stage to load for an asset.
Parameters
----------
category: str
The name of the category the asset belongs to.
parm_id: int
The id of parm to get.
Returns
-------
int
The stage id to load. | scripts/houdini/DigitalAssets/ZefirReader/View.py | getAssetStage | RadicalTeapot/nwave | 0 | python | def getAssetStage(self, category, parm_id):
'Return the stage if of the stage to load for an asset.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to get.\n\n Returns\n -----... | def getAssetStage(self, category, parm_id):
'Return the stage if of the stage to load for an asset.\n\n Parameters\n ----------\n category: str\n The name of the category the asset belongs to.\n parm_id: int\n The id of parm to get.\n\n Returns\n -----... |
95fb9e8b87218d87cacfde4063a4769117c5829d499832881fe7f796e863b94e | @property
def severity(self):
'int: the warning/error flag state.'
return self._node.parm('severity').evalAsInt() | int: the warning/error flag state. | scripts/houdini/DigitalAssets/ZefirReader/View.py | severity | RadicalTeapot/nwave | 0 | python | @property
def severity(self):
return self._node.parm('severity').evalAsInt() | @property
def severity(self):
return self._node.parm('severity').evalAsInt()<|docstring|>int: the warning/error flag state.<|endoftext|> |
bdb7b3ff726bba2415e12d09af1a19324f2c26d6824f5d3e1b7f708d3945337b | @property
def message(self):
'str: the warning/error message.'
return self._node.parm('message').evalAsString() | str: the warning/error message. | scripts/houdini/DigitalAssets/ZefirReader/View.py | message | RadicalTeapot/nwave | 0 | python | @property
def message(self):
return self._node.parm('message').evalAsString() | @property
def message(self):
return self._node.parm('message').evalAsString()<|docstring|>str: the warning/error message.<|endoftext|> |
e5d0825409d7d9fa09aef56e81490f68d90b3f55fe324a05b12ec375d73afcea | def getParmCategoryAndId(self, parm):
"Extract the category and id from a parm.\n\n Parameters\n ----------\n parm: hou.Parm\n The parameter from which to extract the category and id.\n\n Raises\n ------\n RuntimeError\n If the parm category or id cann... | Extract the category and id from a parm.
Parameters
----------
parm: hou.Parm
The parameter from which to extract the category and id.
Raises
------
RuntimeError
If the parm category or id cannot be extracted from it's name.
Returns
-------
str, int
The category and id of the given parm. | scripts/houdini/DigitalAssets/ZefirReader/View.py | getParmCategoryAndId | RadicalTeapot/nwave | 0 | python | def getParmCategoryAndId(self, parm):
"Extract the category and id from a parm.\n\n Parameters\n ----------\n parm: hou.Parm\n The parameter from which to extract the category and id.\n\n Raises\n ------\n RuntimeError\n If the parm category or id cann... | def getParmCategoryAndId(self, parm):
"Extract the category and id from a parm.\n\n Parameters\n ----------\n parm: hou.Parm\n The parameter from which to extract the category and id.\n\n Raises\n ------\n RuntimeError\n If the parm category or id cann... |
6579ba21758c9dbdc5f30c747f450c0004383de88c600eb4ec4fc91dff9fed46 | async def async_setup_entry(hass, config_entry, async_add_devices):
'Add sensors for passed config_entry in HA.'
coordinator = hass.data[DOMAIN][config_entry.entry_id]
tryfi = coordinator.data
new_devices = []
for pet in tryfi.pets:
new_devices.append(TryFiLostMode(hass, pet, coordinator))
... | Add sensors for passed config_entry in HA. | custom_components/tryfi/select.py | async_setup_entry | jldeen/hass-tryfi | 25 | python | async def async_setup_entry(hass, config_entry, async_add_devices):
coordinator = hass.data[DOMAIN][config_entry.entry_id]
tryfi = coordinator.data
new_devices = []
for pet in tryfi.pets:
new_devices.append(TryFiLostMode(hass, pet, coordinator))
if new_devices:
async_add_devices... | async def async_setup_entry(hass, config_entry, async_add_devices):
coordinator = hass.data[DOMAIN][config_entry.entry_id]
tryfi = coordinator.data
new_devices = []
for pet in tryfi.pets:
new_devices.append(TryFiLostMode(hass, pet, coordinator))
if new_devices:
async_add_devices... |
7840ac357f6191ddd484abdbd2adf16501dab8417f4a82e65ab3a5dfe494d35b | def acc(gt, est):
'\n Calculate the accuracy of (agreement between) two interger valued list.\n '
if (len(gt) < 1):
return 1
else:
return (sum([(g == e) for (g, e) in zip(gt, est)]) / len(gt)) | Calculate the accuracy of (agreement between) two interger valued list. | project/vision_backend/utils.py | acc | beijbom/coralnet | 31 | python | def acc(gt, est):
'\n \n '
if (len(gt) < 1):
return 1
else:
return (sum([(g == e) for (g, e) in zip(gt, est)]) / len(gt)) | def acc(gt, est):
'\n \n '
if (len(gt) < 1):
return 1
else:
return (sum([(g == e) for (g, e) in zip(gt, est)]) / len(gt))<|docstring|>Calculate the accuracy of (agreement between) two interger valued list.<|endoftext|> |
6d214928d8f1ace16e9750d925009186cbe20dd84abc40d2dfa515c936a45c9f | def get_label_scores_for_point(point, ordered=False):
"\n :param point: The Point object to get label scores for. Only the top\n NBR_SCORES_PER_ANNOTATION scores are available for each point.\n :param ordered: If True, return the scores in descending order of score\n value. If False, return in a... | :param point: The Point object to get label scores for. Only the top
NBR_SCORES_PER_ANNOTATION scores are available for each point.
:param ordered: If True, return the scores in descending order of score
value. If False, return in arbitrary order (for performance).
:return: {'label': <label code>, 'score': <sco... | project/vision_backend/utils.py | get_label_scores_for_point | beijbom/coralnet | 31 | python | def get_label_scores_for_point(point, ordered=False):
"\n :param point: The Point object to get label scores for. Only the top\n NBR_SCORES_PER_ANNOTATION scores are available for each point.\n :param ordered: If True, return the scores in descending order of score\n value. If False, return in a... | def get_label_scores_for_point(point, ordered=False):
"\n :param point: The Point object to get label scores for. Only the top\n NBR_SCORES_PER_ANNOTATION scores are available for each point.\n :param ordered: If True, return the scores in descending order of score\n value. If False, return in a... |
3b530cd1fe8619263fc8c5df7b367c2d719cc55ef69b0a550cf3c08dc895d54c | def get_label_scores_for_image(image_id):
"\n Return all the saved label scores for an image in this format:\n {1: [{'label': 'Acrop', 'score': 14},\n {'label': 'Porit', 'score': 21},\n ...],\n 2: [...], ...}\n Where the top-level dict's keys are the point numbers.\n "
lpdict = {... | Return all the saved label scores for an image in this format:
{1: [{'label': 'Acrop', 'score': 14},
{'label': 'Porit', 'score': 21},
...],
2: [...], ...}
Where the top-level dict's keys are the point numbers. | project/vision_backend/utils.py | get_label_scores_for_image | beijbom/coralnet | 31 | python | def get_label_scores_for_image(image_id):
"\n Return all the saved label scores for an image in this format:\n {1: [{'label': 'Acrop', 'score': 14},\n {'label': 'Porit', 'score': 21},\n ...],\n 2: [...], ...}\n Where the top-level dict's keys are the point numbers.\n "
lpdict = {... | def get_label_scores_for_image(image_id):
"\n Return all the saved label scores for an image in this format:\n {1: [{'label': 'Acrop', 'score': 14},\n {'label': 'Porit', 'score': 21},\n ...],\n 2: [...], ...}\n Where the top-level dict's keys are the point numbers.\n "
lpdict = {... |
8ba40fae0739807aef58a5c8075748d8ca61463f81925278611145327c7978ef | def get_alleviate(estlabels, gtlabels, scores):
'\n calculates accuracy for (up to) 250 different score thresholds.\n '
if ((not (len(estlabels) == len(gtlabels))) or (not (len(estlabels) == len(scores)))):
raise ValueError('all inputs must have the same length')
if (len(estlabels) == 0):
... | calculates accuracy for (up to) 250 different score thresholds. | project/vision_backend/utils.py | get_alleviate | beijbom/coralnet | 31 | python | def get_alleviate(estlabels, gtlabels, scores):
'\n \n '
if ((not (len(estlabels) == len(gtlabels))) or (not (len(estlabels) == len(scores)))):
raise ValueError('all inputs must have the same length')
if (len(estlabels) == 0):
raise ValueError('inputs must have length > 0')
scores ... | def get_alleviate(estlabels, gtlabels, scores):
'\n \n '
if ((not (len(estlabels) == len(gtlabels))) or (not (len(estlabels) == len(scores)))):
raise ValueError('all inputs must have the same length')
if (len(estlabels) == 0):
raise ValueError('inputs must have length > 0')
scores ... |
522b93cdc1df81e5fb8cf6bd6022b2ae4d4eaf47439b9f9905388e698075ee04 | def map_labels(labellist, classmap):
'\n Helper function to map integer labels to new labels.\n '
labellist = np.asarray(labellist, dtype=np.int)
newlist = ((- 1) * np.ones(len(labellist), dtype=np.int))
for key in classmap.keys():
newlist[(labellist == key)] = classmap[key]
return lis... | Helper function to map integer labels to new labels. | project/vision_backend/utils.py | map_labels | beijbom/coralnet | 31 | python | def map_labels(labellist, classmap):
'\n \n '
labellist = np.asarray(labellist, dtype=np.int)
newlist = ((- 1) * np.ones(len(labellist), dtype=np.int))
for key in classmap.keys():
newlist[(labellist == key)] = classmap[key]
return list(newlist) | def map_labels(labellist, classmap):
'\n \n '
labellist = np.asarray(labellist, dtype=np.int)
newlist = ((- 1) * np.ones(len(labellist), dtype=np.int))
for key in classmap.keys():
newlist[(labellist == key)] = classmap[key]
return list(newlist)<|docstring|>Helper function to map intege... |
5a0e7e63411160bd62bf7ac7d1e2bb22faa6eeb6513279e09549902309e9727b | def labelset_mapper(labelmode, classids, source):
'\n Prepares mapping function and labelset names to inject in confusion matrix.\n '
if (labelmode == 'full'):
classnames = [Label.objects.get(id=classid).name for classid in classids]
codes = [LocalLabel.objects.get(global_label__id=class_i... | Prepares mapping function and labelset names to inject in confusion matrix. | project/vision_backend/utils.py | labelset_mapper | beijbom/coralnet | 31 | python | def labelset_mapper(labelmode, classids, source):
'\n \n '
if (labelmode == 'full'):
classnames = [Label.objects.get(id=classid).name for classid in classids]
codes = [LocalLabel.objects.get(global_label__id=class_id, labelset=source.labelset).code for class_id in classids]
classma... | def labelset_mapper(labelmode, classids, source):
'\n \n '
if (labelmode == 'full'):
classnames = [Label.objects.get(id=classid).name for classid in classids]
codes = [LocalLabel.objects.get(global_label__id=class_id, labelset=source.labelset).code for class_id in classids]
classma... |
f4111267429d5fed2cb401e04baadc51c6c3603a6194d59f108cbd5be4dc0a66 | def check_col_dict(fname, col_dict):
'\n Arg:\n - fname: file name\n - col_dict: {year: {ftype: {tab_num:#, start_row:#, end_row:#, cols:[]}}}\n Return:\n - ftype\n - tab_num\n - start_row\n - end_row\n - cols: list of column indexes\n '
year = fname[:7]... | Arg:
- fname: file name
- col_dict: {year: {ftype: {tab_num:#, start_row:#, end_row:#, cols:[]}}}
Return:
- ftype
- tab_num
- start_row
- end_row
- cols: list of column indexes | vaxxfacts/data_load/processing_helper.py | check_col_dict | jeffrey-hsu/mids_capstone | 0 | python | def check_col_dict(fname, col_dict):
'\n Arg:\n - fname: file name\n - col_dict: {year: {ftype: {tab_num:#, start_row:#, end_row:#, cols:[]}}}\n Return:\n - ftype\n - tab_num\n - start_row\n - end_row\n - cols: list of column indexes\n '
year = fname[:7]... | def check_col_dict(fname, col_dict):
'\n Arg:\n - fname: file name\n - col_dict: {year: {ftype: {tab_num:#, start_row:#, end_row:#, cols:[]}}}\n Return:\n - ftype\n - tab_num\n - start_row\n - end_row\n - cols: list of column indexes\n '
year = fname[:7]... |
d8dbca81e8aa10534d9377a8d5133dd97d4e5a04813b4fe3870b0cd22da9c3e6 | def merge_csv(input_files, output_file_path, cols):
'\n Arg:\n - input_files : [input_file_path]\n - output_file_path : string path\n - cols : [column definition]\n '
final_df = pd.DataFrame([])
for (i, input_file) in enumerate(input_files):
df = pd.read_csv(input_file, sk... | Arg:
- input_files : [input_file_path]
- output_file_path : string path
- cols : [column definition] | vaxxfacts/data_load/processing_helper.py | merge_csv | jeffrey-hsu/mids_capstone | 0 | python | def merge_csv(input_files, output_file_path, cols):
'\n Arg:\n - input_files : [input_file_path]\n - output_file_path : string path\n - cols : [column definition]\n '
final_df = pd.DataFrame([])
for (i, input_file) in enumerate(input_files):
df = pd.read_csv(input_file, sk... | def merge_csv(input_files, output_file_path, cols):
'\n Arg:\n - input_files : [input_file_path]\n - output_file_path : string path\n - cols : [column definition]\n '
final_df = pd.DataFrame([])
for (i, input_file) in enumerate(input_files):
df = pd.read_csv(input_file, sk... |
107edca44663aadeea8a4b00d6968c6589d435b41f84ae7183be57b4c100362f | def __init__(self, num_tasks: int, per_task_examples: Optional[int]=None, per_task_joint_examples: Optional[int]=0, per_task_memory_examples: Optional[int]=0, per_task_subset_examples: Optional[int]=0, task_input_transforms: Optional[list]=None, task_target_transforms: Optional[list]=None):
'\n Args:\n ... | Args:
num_tasks: The number of tasks for the benchmark.
per_task_examples: If set, each task will include part of the original benchmark rather than full data.
per_task_joint_examples: If set, the benchmark will support joint/multitask loading of tasks.
per_task_memory_examples: If set, the benchmark wi... | cl_gym/benchmarks/mnist.py | __init__ | imirzadeh/CL-Gym | 26 | python | def __init__(self, num_tasks: int, per_task_examples: Optional[int]=None, per_task_joint_examples: Optional[int]=0, per_task_memory_examples: Optional[int]=0, per_task_subset_examples: Optional[int]=0, task_input_transforms: Optional[list]=None, task_target_transforms: Optional[list]=None):
'\n Args:\n ... | def __init__(self, num_tasks: int, per_task_examples: Optional[int]=None, per_task_joint_examples: Optional[int]=0, per_task_memory_examples: Optional[int]=0, per_task_subset_examples: Optional[int]=0, task_input_transforms: Optional[list]=None, task_target_transforms: Optional[list]=None):
'\n Args:\n ... |
54274c881211387733f4e4f27842fb8721f6b1fdf4c5c3acc0c10225fe49a108 | def __init__(self, num_tasks: int, per_task_examples: Optional[int]=None, per_task_joint_examples: Optional[int]=0, per_task_memory_examples: Optional[int]=0, per_task_subset_examples: Optional[int]=0, task_input_transforms: Optional[list]=None, task_target_transforms: Optional[list]=None, per_task_rotation: Optional[f... | Args:
num_tasks: The number of tasks for the benchmark.
per_task_examples: If set, each task will include part of the original benchmark rather than full data.
per_task_joint_examples: If set, the benchmark will support joint/multitask loading of tasks.
per_task_memory_examples: If set, the benchmark wi... | cl_gym/benchmarks/mnist.py | __init__ | imirzadeh/CL-Gym | 26 | python | def __init__(self, num_tasks: int, per_task_examples: Optional[int]=None, per_task_joint_examples: Optional[int]=0, per_task_memory_examples: Optional[int]=0, per_task_subset_examples: Optional[int]=0, task_input_transforms: Optional[list]=None, task_target_transforms: Optional[list]=None, per_task_rotation: Optional[f... | def __init__(self, num_tasks: int, per_task_examples: Optional[int]=None, per_task_joint_examples: Optional[int]=0, per_task_memory_examples: Optional[int]=0, per_task_subset_examples: Optional[int]=0, task_input_transforms: Optional[list]=None, task_target_transforms: Optional[list]=None, per_task_rotation: Optional[f... |
9baa6c23f8a63203e753c4d588c8f6113865aef8a6144713badb346aee9dda2d | def __init__(self, num_tasks: int, per_task_examples: Optional[int]=None, per_task_joint_examples: Optional[int]=0, per_task_memory_examples: Optional[int]=0, per_task_subset_examples: Optional[int]=0, task_input_transforms: Optional[list]=None, task_target_transforms: Optional[list]=None):
'\n Args:\n ... | Args:
num_tasks: The number of tasks for the benchmark.
per_task_examples: If set, each task will include part of the original benchmark rather than full data.
per_task_joint_examples: If set, the benchmark will support joint/multitask loading of tasks.
per_task_memory_examples: If set, the benchmark wi... | cl_gym/benchmarks/mnist.py | __init__ | imirzadeh/CL-Gym | 26 | python | def __init__(self, num_tasks: int, per_task_examples: Optional[int]=None, per_task_joint_examples: Optional[int]=0, per_task_memory_examples: Optional[int]=0, per_task_subset_examples: Optional[int]=0, task_input_transforms: Optional[list]=None, task_target_transforms: Optional[list]=None):
'\n Args:\n ... | def __init__(self, num_tasks: int, per_task_examples: Optional[int]=None, per_task_joint_examples: Optional[int]=0, per_task_memory_examples: Optional[int]=0, per_task_subset_examples: Optional[int]=0, task_input_transforms: Optional[list]=None, task_target_transforms: Optional[list]=None):
'\n Args:\n ... |
26c860163031dc6b34da6c4b69ba32940ed110b65a08048404e5f793adb6a922 | def evaluate_pos(test_x, test_y, model_DC, total_batches_test, batch_size, proj, W):
'\n evaluation for both the dev and test set\n calculates the accuracy for the corresponding dataset\n '
correct = 0
indices = torch.randperm(len(test_x))
for i in range(total_batches_test):
index = ind... | evaluation for both the dev and test set
calculates the accuracy for the corresponding dataset | Assignment2/train_pos.py | evaluate_pos | TimO96/NLP2 | 0 | python | def evaluate_pos(test_x, test_y, model_DC, total_batches_test, batch_size, proj, W):
'\n evaluation for both the dev and test set\n calculates the accuracy for the corresponding dataset\n '
correct = 0
indices = torch.randperm(len(test_x))
for i in range(total_batches_test):
index = ind... | def evaluate_pos(test_x, test_y, model_DC, total_batches_test, batch_size, proj, W):
'\n evaluation for both the dev and test set\n calculates the accuracy for the corresponding dataset\n '
correct = 0
indices = torch.randperm(len(test_x))
for i in range(total_batches_test):
index = ind... |
33b449fa38e6ce412c689619ad3ec74d4e1d0bb39c530b80e153628176fb776d | def train(data_x, data_y, W=None, proj=True):
'\n Performs the training of the POS-tagging task\n Returns the accuracy that is obtained from the test set\n '
learning_rate = 0.001
batch_size = 64
epochs = 100
embed_size = 768
loss = nn.CrossEntropyLoss()
train_x = data_x['train']
... | Performs the training of the POS-tagging task
Returns the accuracy that is obtained from the test set | Assignment2/train_pos.py | train | TimO96/NLP2 | 0 | python | def train(data_x, data_y, W=None, proj=True):
'\n Performs the training of the POS-tagging task\n Returns the accuracy that is obtained from the test set\n '
learning_rate = 0.001
batch_size = 64
epochs = 100
embed_size = 768
loss = nn.CrossEntropyLoss()
train_x = data_x['train']
... | def train(data_x, data_y, W=None, proj=True):
'\n Performs the training of the POS-tagging task\n Returns the accuracy that is obtained from the test set\n '
learning_rate = 0.001
batch_size = 64
epochs = 100
embed_size = 768
loss = nn.CrossEntropyLoss()
train_x = data_x['train']
... |
16e1a0c161bb020e1332cca5f3a298df98d4ccf8ff77203dfab656972415429a | def step(self, e, dt):
'\n :param e: error\n :param dt: should be the time elapsed from the last time step was called\n :return output: speed\n '
if (self.last_e is not None):
derivative = ((e - self.last_e) / dt)
else:
derivative = 0
self.last_e = e
self.... | :param e: error
:param dt: should be the time elapsed from the last time step was called
:return output: speed | source/controllers/pid.py | step | GiorgiaAuroraAdorni/learning-robot-swarm-controllers | 0 | python | def step(self, e, dt):
'\n :param e: error\n :param dt: should be the time elapsed from the last time step was called\n :return output: speed\n '
if (self.last_e is not None):
derivative = ((e - self.last_e) / dt)
else:
derivative = 0
self.last_e = e
self.... | def step(self, e, dt):
'\n :param e: error\n :param dt: should be the time elapsed from the last time step was called\n :return output: speed\n '
if (self.last_e is not None):
derivative = ((e - self.last_e) / dt)
else:
derivative = 0
self.last_e = e
self.... |
65c5ccd1744ab049567abdfc87564df076b92c96734d065cc68a229749d8c87f | def _importInDjango(self):
' Import data to django from csv '
with open(settings.DATA_PATH, 'r', encoding='latin-1') as csv_file:
reader = csv.DictReader(csv_file, delimiter=';')
for raw in reader:
(division, created) = Division.objects.get_or_create(nom=raw['Division'])
... | Import data to django from csv | score/management/commands/import.py | _importInDjango | loric-/bcvscore | 1 | python | def _importInDjango(self):
' '
with open(settings.DATA_PATH, 'r', encoding='latin-1') as csv_file:
reader = csv.DictReader(csv_file, delimiter=';')
for raw in reader:
(division, created) = Division.objects.get_or_create(nom=raw['Division'])
if created:
se... | def _importInDjango(self):
' '
with open(settings.DATA_PATH, 'r', encoding='latin-1') as csv_file:
reader = csv.DictReader(csv_file, delimiter=';')
for raw in reader:
(division, created) = Division.objects.get_or_create(nom=raw['Division'])
if created:
se... |
5b440e48fc73e44c1736f20019165e2804682e77786f3e7b28a224863ebdcd82 | def _downloadDataFile(self):
' Download csv file from ffbb '
config = SiteConfiguration.objects.get()
with requests.Session() as s:
data = {'identificationBean.identifiant': '{}'.format(config.login), 'identificationBean.mdp': '{}'.format(config.password), 'userName': '{}'.format(config.username)}
... | Download csv file from ffbb | score/management/commands/import.py | _downloadDataFile | loric-/bcvscore | 1 | python | def _downloadDataFile(self):
' '
config = SiteConfiguration.objects.get()
with requests.Session() as s:
data = {'identificationBean.identifiant': '{}'.format(config.login), 'identificationBean.mdp': '{}'.format(config.password), 'userName': '{}'.format(config.username)}
url = 'http://extran... | def _downloadDataFile(self):
' '
config = SiteConfiguration.objects.get()
with requests.Session() as s:
data = {'identificationBean.identifiant': '{}'.format(config.login), 'identificationBean.mdp': '{}'.format(config.password), 'userName': '{}'.format(config.username)}
url = 'http://extran... |
27a361e68219092627fc1f162dae279039a6ddeaf2064d1d24c044b700755686 | @receiver(governance_process_updated, sender=SlackEmojiVote)
def slack_vote_updated_receiver(sender, instance, status, outcome, errors, **kwargs):
'\n Handle a change to an ongoing Metagov slack.emoji-vote GovernanceProcess.\n This function gets called any time a slack.emoji-vote gets updated (e.g. if a vote ... | Handle a change to an ongoing Metagov slack.emoji-vote GovernanceProcess.
This function gets called any time a slack.emoji-vote gets updated (e.g. if a vote was cast). | policykit/integrations/slack/handlers.py | slack_vote_updated_receiver | mashton/policyk | 0 | python | @receiver(governance_process_updated, sender=SlackEmojiVote)
def slack_vote_updated_receiver(sender, instance, status, outcome, errors, **kwargs):
'\n Handle a change to an ongoing Metagov slack.emoji-vote GovernanceProcess.\n This function gets called any time a slack.emoji-vote gets updated (e.g. if a vote ... | @receiver(governance_process_updated, sender=SlackEmojiVote)
def slack_vote_updated_receiver(sender, instance, status, outcome, errors, **kwargs):
'\n Handle a change to an ongoing Metagov slack.emoji-vote GovernanceProcess.\n This function gets called any time a slack.emoji-vote gets updated (e.g. if a vote ... |
8f72b14545b79d3e6ff3dc1ba3731e072f779491ef588dd2a8748c00346e6aa2 | def save_image_crop(image_uri, image_crop_uri, label_uri=None, label_crop_uri=None, size=600, min_features=10, vector_labels=True, class_config=None):
'Save a crop of an image to use for testing.\n\n If label_uri is set, the crop needs to cover >= min_features.\n\n Args:\n image_uri: URI of original im... | Save a crop of an image to use for testing.
If label_uri is set, the crop needs to cover >= min_features.
Args:
image_uri: URI of original image
image_crop_uri: URI of cropped image to save
label_uri: optional URI of label file
label_crop_uri: optional URI of cropped labels to save
size: height an... | rastervision_pytorch_backend/rastervision/pytorch_backend/examples/utils.py | save_image_crop | theoway/raster-vision | 1,577 | python | def save_image_crop(image_uri, image_crop_uri, label_uri=None, label_crop_uri=None, size=600, min_features=10, vector_labels=True, class_config=None):
'Save a crop of an image to use for testing.\n\n If label_uri is set, the crop needs to cover >= min_features.\n\n Args:\n image_uri: URI of original im... | def save_image_crop(image_uri, image_crop_uri, label_uri=None, label_crop_uri=None, size=600, min_features=10, vector_labels=True, class_config=None):
'Save a crop of an image to use for testing.\n\n If label_uri is set, the crop needs to cover >= min_features.\n\n Args:\n image_uri: URI of original im... |
a8720c22a2a91895a1b798635e96db4652f25c69db4bba518785365f2b47fcca | def read_stac(uri: str, unzip_dir: Optional[str]=None) -> List[dict]:
'Parse the contents of a STAC catalog (downloading it first, if\n remote). If the uri is a zip file, unzip it, find catalog.json inside it\n and parse that.\n\n Args:\n uri (str): Either a URI to a STAC catalog JSON file or a URI ... | Parse the contents of a STAC catalog (downloading it first, if
remote). If the uri is a zip file, unzip it, find catalog.json inside it
and parse that.
Args:
uri (str): Either a URI to a STAC catalog JSON file or a URI to a zip
file containing a STAC catalog JSON file.
Raises:
FileNotFoundError: If ca... | rastervision_pytorch_backend/rastervision/pytorch_backend/examples/utils.py | read_stac | theoway/raster-vision | 1,577 | python | def read_stac(uri: str, unzip_dir: Optional[str]=None) -> List[dict]:
'Parse the contents of a STAC catalog (downloading it first, if\n remote). If the uri is a zip file, unzip it, find catalog.json inside it\n and parse that.\n\n Args:\n uri (str): Either a URI to a STAC catalog JSON file or a URI ... | def read_stac(uri: str, unzip_dir: Optional[str]=None) -> List[dict]:
'Parse the contents of a STAC catalog (downloading it first, if\n remote). If the uri is a zip file, unzip it, find catalog.json inside it\n and parse that.\n\n Args:\n uri (str): Either a URI to a STAC catalog JSON file or a URI ... |
f23001fe80eb94031e4bc0cab92dfd5000a7a9654aedbf7f058a1d5b5d9c1967 | def image_upload_url(recipe_id):
'Return url for recipe image upload'
return reverse('recipe:recipe-upload-image', args=[recipe_id]) | Return url for recipe image upload | app/recipe/tests/test_recipe_api.py | image_upload_url | borismu/django-rest-recipes | 0 | python | def image_upload_url(recipe_id):
return reverse('recipe:recipe-upload-image', args=[recipe_id]) | def image_upload_url(recipe_id):
return reverse('recipe:recipe-upload-image', args=[recipe_id])<|docstring|>Return url for recipe image upload<|endoftext|> |
abb070a0b4e0c9ff1d3450e5afb23d7846a78b332f46dd64703b6310991f421f | def sample_tag(user, name='Main course'):
'Create and return a sample tag'
return Tag.objects.create(user=user, name=name) | Create and return a sample tag | app/recipe/tests/test_recipe_api.py | sample_tag | borismu/django-rest-recipes | 0 | python | def sample_tag(user, name='Main course'):
return Tag.objects.create(user=user, name=name) | def sample_tag(user, name='Main course'):
return Tag.objects.create(user=user, name=name)<|docstring|>Create and return a sample tag<|endoftext|> |
cdd634b966fef2c76f338d759e83614cf28d96475631c94954614176626854b0 | def sample_ingredient(user, name='Main course'):
'Create and return a sample ingredient'
return Ingredient.objects.create(user=user, name=name) | Create and return a sample ingredient | app/recipe/tests/test_recipe_api.py | sample_ingredient | borismu/django-rest-recipes | 0 | python | def sample_ingredient(user, name='Main course'):
return Ingredient.objects.create(user=user, name=name) | def sample_ingredient(user, name='Main course'):
return Ingredient.objects.create(user=user, name=name)<|docstring|>Create and return a sample ingredient<|endoftext|> |
9b531a4d8682dc1c420a13778db57a4ddaed3c9c896baf4a32f2118788402b4a | def recipe_detail_url(recipe_id):
'Return url for recipe '
return reverse('recipe:recipe-detail', args=[recipe_id]) | Return url for recipe | app/recipe/tests/test_recipe_api.py | recipe_detail_url | borismu/django-rest-recipes | 0 | python | def recipe_detail_url(recipe_id):
' '
return reverse('recipe:recipe-detail', args=[recipe_id]) | def recipe_detail_url(recipe_id):
' '
return reverse('recipe:recipe-detail', args=[recipe_id])<|docstring|>Return url for recipe<|endoftext|> |
8fa8f1faafde2c910c642de7dd84c67725da561ce75cbe077b18adff79a8f840 | def sample_recipe(user, **params):
'Create and return a sample recipe'
defaults = {'title': 'Sample recipe', 'time_minutes': 10, 'price': 5.0}
defaults.update(params)
return Recipe.objects.create(user=user, **defaults) | Create and return a sample recipe | app/recipe/tests/test_recipe_api.py | sample_recipe | borismu/django-rest-recipes | 0 | python | def sample_recipe(user, **params):
defaults = {'title': 'Sample recipe', 'time_minutes': 10, 'price': 5.0}
defaults.update(params)
return Recipe.objects.create(user=user, **defaults) | def sample_recipe(user, **params):
defaults = {'title': 'Sample recipe', 'time_minutes': 10, 'price': 5.0}
defaults.update(params)
return Recipe.objects.create(user=user, **defaults)<|docstring|>Create and return a sample recipe<|endoftext|> |
90052b664bfefe89bb1d9328e945c8bac8df8b4381571c9c06f37846fe2a9fe5 | def test_auth_required(self):
'Test that authentication is required'
res = self.client.get(RECIPES_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | Test that authentication is required | app/recipe/tests/test_recipe_api.py | test_auth_required | borismu/django-rest-recipes | 0 | python | def test_auth_required(self):
res = self.client.get(RECIPES_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | def test_auth_required(self):
res = self.client.get(RECIPES_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)<|docstring|>Test that authentication is required<|endoftext|> |
4e686a350d6d3aadc9e33225884cb806b58f8e487d989ff11a8d645cb7a0425b | def test_retrieve_recipes(self):
'Test retrieving a list of recipes'
sample_recipe(user=self.user)
sample_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.all().order_by('-id')
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_cod... | Test retrieving a list of recipes | app/recipe/tests/test_recipe_api.py | test_retrieve_recipes | borismu/django-rest-recipes | 0 | python | def test_retrieve_recipes(self):
sample_recipe(user=self.user)
sample_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.all().order_by('-id')
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.ass... | def test_retrieve_recipes(self):
sample_recipe(user=self.user)
sample_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.all().order_by('-id')
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.ass... |
2030f47a37d7c1314ccf3844bd887994a5755c34f512b2ec6d8852bb248157e2 | def test_recipes_limited_to_user(self):
'Test retrieving recipes for user'
user2 = get_user_model().objects.create_user('example@example.com', 'testpass2')
sample_recipe(user=user2)
sample_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.filter(user=self.user)
... | Test retrieving recipes for user | app/recipe/tests/test_recipe_api.py | test_recipes_limited_to_user | borismu/django-rest-recipes | 0 | python | def test_recipes_limited_to_user(self):
user2 = get_user_model().objects.create_user('example@example.com', 'testpass2')
sample_recipe(user=user2)
sample_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.filter(user=self.user)
serializer = RecipeSerializer(r... | def test_recipes_limited_to_user(self):
user2 = get_user_model().objects.create_user('example@example.com', 'testpass2')
sample_recipe(user=user2)
sample_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.filter(user=self.user)
serializer = RecipeSerializer(r... |
66df2dc0c400260ca4a5881b29ad7b2cfb670eb0e71b85d887137ff4d2dd803b | def test_view_recipe_detail(self):
'Test viewing a recipe detail'
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
recipe.ingredients.add(sample_ingredient(user=self.user))
url = recipe_detail_url(recipe.id)
res = self.client.get(url)
serializer = RecipeDeta... | Test viewing a recipe detail | app/recipe/tests/test_recipe_api.py | test_view_recipe_detail | borismu/django-rest-recipes | 0 | python | def test_view_recipe_detail(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
recipe.ingredients.add(sample_ingredient(user=self.user))
url = recipe_detail_url(recipe.id)
res = self.client.get(url)
serializer = RecipeDetailSerializer(recipe)
self.... | def test_view_recipe_detail(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
recipe.ingredients.add(sample_ingredient(user=self.user))
url = recipe_detail_url(recipe.id)
res = self.client.get(url)
serializer = RecipeDetailSerializer(recipe)
self.... |
684101836aae1ee13f4f229e651b77f83df9eec23266e06d5b546a5743566423 | def test_create_basic_recipe(self):
'Test creating recipe'
payload = {'title': 'Brauni', 'time_minutes': 30, 'price': 5.0}
res = self.client.post(RECIPES_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=res.data['id'])
for key in payload.key... | Test creating recipe | app/recipe/tests/test_recipe_api.py | test_create_basic_recipe | borismu/django-rest-recipes | 0 | python | def test_create_basic_recipe(self):
payload = {'title': 'Brauni', 'time_minutes': 30, 'price': 5.0}
res = self.client.post(RECIPES_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=res.data['id'])
for key in payload.keys():
self.asse... | def test_create_basic_recipe(self):
payload = {'title': 'Brauni', 'time_minutes': 30, 'price': 5.0}
res = self.client.post(RECIPES_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=res.data['id'])
for key in payload.keys():
self.asse... |
d8c40fdffc1043cb619f461567e14d943f11435fb5392e230f44fb17461af1b0 | def test_create_recipe_with_tags(self):
'Test creating a recipe with tags'
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Dessert')
payload = {'title': 'Fruit salad', 'tags': [tag1.id, tag2.id], 'time_minutes': 10, 'price': 12.0}
res = self.client.post(RECIPE... | Test creating a recipe with tags | app/recipe/tests/test_recipe_api.py | test_create_recipe_with_tags | borismu/django-rest-recipes | 0 | python | def test_create_recipe_with_tags(self):
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Dessert')
payload = {'title': 'Fruit salad', 'tags': [tag1.id, tag2.id], 'time_minutes': 10, 'price': 12.0}
res = self.client.post(RECIPES_URL, payload)
self.assertEqu... | def test_create_recipe_with_tags(self):
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Dessert')
payload = {'title': 'Fruit salad', 'tags': [tag1.id, tag2.id], 'time_minutes': 10, 'price': 12.0}
res = self.client.post(RECIPES_URL, payload)
self.assertEqu... |
37ed178b4cb11adfa4e780de352ff8452fce8d5183c7a5e0228d80cfd36bcc47 | def test_create_recipe_with_ingredients(self):
'Test creating a recipe with ingredients'
ingredient1 = sample_ingredient(user=self.user, name='Banana')
ingredient2 = sample_ingredient(user=self.user, name='Orange')
payload = {'title': 'Fruit salad', 'ingredients': [ingredient1.id, ingredient2.id], 'time... | Test creating a recipe with ingredients | app/recipe/tests/test_recipe_api.py | test_create_recipe_with_ingredients | borismu/django-rest-recipes | 0 | python | def test_create_recipe_with_ingredients(self):
ingredient1 = sample_ingredient(user=self.user, name='Banana')
ingredient2 = sample_ingredient(user=self.user, name='Orange')
payload = {'title': 'Fruit salad', 'ingredients': [ingredient1.id, ingredient2.id], 'time_minutes': 10, 'price': 12.0}
res = s... | def test_create_recipe_with_ingredients(self):
ingredient1 = sample_ingredient(user=self.user, name='Banana')
ingredient2 = sample_ingredient(user=self.user, name='Orange')
payload = {'title': 'Fruit salad', 'ingredients': [ingredient1.id, ingredient2.id], 'time_minutes': 10, 'price': 12.0}
res = s... |
1cf6b0669d2cea43c19117c90ec1ebb9705f136e39a24cc869dc77c25b3b0646 | def test_partial_update_recipe(self):
'Test updating a recipe with patch'
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
new_tag = sample_tag(user=self.user, name='Curry')
payload = {'title': 'Chicken Tikka', 'tags': [new_tag.id]}
url = recipe_detail_url(recip... | Test updating a recipe with patch | app/recipe/tests/test_recipe_api.py | test_partial_update_recipe | borismu/django-rest-recipes | 0 | python | def test_partial_update_recipe(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
new_tag = sample_tag(user=self.user, name='Curry')
payload = {'title': 'Chicken Tikka', 'tags': [new_tag.id]}
url = recipe_detail_url(recipe.id)
self.client.patch(url, pa... | def test_partial_update_recipe(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
new_tag = sample_tag(user=self.user, name='Curry')
payload = {'title': 'Chicken Tikka', 'tags': [new_tag.id]}
url = recipe_detail_url(recipe.id)
self.client.patch(url, pa... |
cbe9705286957d4c21d67c3c80f80efb0b52a1714b745afc0e84848aab4add29 | def test_full_update_recipe(self):
'Test updating a recipe with put'
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
payload = {'title': 'Spaghetti', 'time_minutes': 10, 'price': 16.0}
url = recipe_detail_url(recipe.id)
self.client.put(url, payload)
recipe.... | Test updating a recipe with put | app/recipe/tests/test_recipe_api.py | test_full_update_recipe | borismu/django-rest-recipes | 0 | python | def test_full_update_recipe(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
payload = {'title': 'Spaghetti', 'time_minutes': 10, 'price': 16.0}
url = recipe_detail_url(recipe.id)
self.client.put(url, payload)
recipe.refresh_from_db()
self.assert... | def test_full_update_recipe(self):
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
payload = {'title': 'Spaghetti', 'time_minutes': 10, 'price': 16.0}
url = recipe_detail_url(recipe.id)
self.client.put(url, payload)
recipe.refresh_from_db()
self.assert... |
946ac9955a11ceb373871882de33ec2021e8dd642c703c3e27d88dc150c741bf | def test_filter_recipes_by_tags(self):
'Test returning recipes with specific tags'
recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry')
recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini')
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.... | Test returning recipes with specific tags | app/recipe/tests/test_recipe_api.py | test_filter_recipes_by_tags | borismu/django-rest-recipes | 0 | python | def test_filter_recipes_by_tags(self):
recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry')
recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini')
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Vegetarian')
recipe1.tags.a... | def test_filter_recipes_by_tags(self):
recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry')
recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini')
tag1 = sample_tag(user=self.user, name='Vegan')
tag2 = sample_tag(user=self.user, name='Vegetarian')
recipe1.tags.a... |
61eb436625c42332fb225183f9ce5af843b6ff42f5392746069e580ba19edb30 | def test_filter_recipes_by_ingredients(self):
'Test returning recipes with specific ingredients'
recipe1 = sample_recipe(user=self.user, title='Posh beans on toast')
recipe2 = sample_recipe(user=self.user, title='Chicken cacciatore')
ingredient1 = sample_ingredient(user=self.user, name='Feta cheese')
... | Test returning recipes with specific ingredients | app/recipe/tests/test_recipe_api.py | test_filter_recipes_by_ingredients | borismu/django-rest-recipes | 0 | python | def test_filter_recipes_by_ingredients(self):
recipe1 = sample_recipe(user=self.user, title='Posh beans on toast')
recipe2 = sample_recipe(user=self.user, title='Chicken cacciatore')
ingredient1 = sample_ingredient(user=self.user, name='Feta cheese')
ingredient2 = sample_ingredient(user=self.user, ... | def test_filter_recipes_by_ingredients(self):
recipe1 = sample_recipe(user=self.user, title='Posh beans on toast')
recipe2 = sample_recipe(user=self.user, title='Chicken cacciatore')
ingredient1 = sample_ingredient(user=self.user, name='Feta cheese')
ingredient2 = sample_ingredient(user=self.user, ... |
cf9bbb8f672cb65e128e02fda336e27b9588c35a19fedf217f77360411945eff | def test_upload_image_to_recipe(self):
'Test uploading an image to recipe'
url = image_upload_url(self.recipe.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10))
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(url, {'im... | Test uploading an image to recipe | app/recipe/tests/test_recipe_api.py | test_upload_image_to_recipe | borismu/django-rest-recipes | 0 | python | def test_upload_image_to_recipe(self):
url = image_upload_url(self.recipe.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10))
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(url, {'image': ntf}, format='multipart')
... | def test_upload_image_to_recipe(self):
url = image_upload_url(self.recipe.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10))
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(url, {'image': ntf}, format='multipart')
... |
b77bff89e22b1a39e30f0acbbbffd9c00e097d1aa3fa72857c7b4f0dd2f880d6 | def test_upload_image_bad_request(self):
'Test uploading invalid image'
url = image_upload_url(self.recipe.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | Test uploading invalid image | app/recipe/tests/test_recipe_api.py | test_upload_image_bad_request | borismu/django-rest-recipes | 0 | python | def test_upload_image_bad_request(self):
url = image_upload_url(self.recipe.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | def test_upload_image_bad_request(self):
url = image_upload_url(self.recipe.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)<|docstring|>Test uploading invalid image<|endoftext|> |
6195f7816bf0b43ae45d3277c166c32315f3234309b35d69371b141f79d03b5a | def make_password(password, salt=None, hasher='default', **kwargs):
'\n Turn a plain-text password into a hash for database storage\n\n Same as encode() but generates a new random salt.\n If password is None then a concatenation of\n UNUSABLE_PASSWORD_PREFIX and a random string will be returned\n whi... | Turn a plain-text password into a hash for database storage
Same as encode() but generates a new random salt.
If password is None then a concatenation of
UNUSABLE_PASSWORD_PREFIX and a random string will be returned
which disallows logins. Additional random string reduces chances
of gaining access to staff or superuse... | libsousou/hashers/base.py | make_password | sousouindustries/python-libsousou | 0 | python | def make_password(password, salt=None, hasher='default', **kwargs):
'\n Turn a plain-text password into a hash for database storage\n\n Same as encode() but generates a new random salt.\n If password is None then a concatenation of\n UNUSABLE_PASSWORD_PREFIX and a random string will be returned\n whi... | def make_password(password, salt=None, hasher='default', **kwargs):
'\n Turn a plain-text password into a hash for database storage\n\n Same as encode() but generates a new random salt.\n If password is None then a concatenation of\n UNUSABLE_PASSWORD_PREFIX and a random string will be returned\n whi... |
f7e6c8b321c81275827c9cd4fc060de500c7aae9058935d34fc4a533f0132942 | def check_password(password, encoded, setter=None, preferred='default'):
"\n Returns a boolean of whether the raw password matches the three\n part encoded digest.\n\n If setter is specified, it'll be called when you need to\n regenerate the password.\n "
if ((password is None) or (not is_passwor... | Returns a boolean of whether the raw password matches the three
part encoded digest.
If setter is specified, it'll be called when you need to
regenerate the password. | libsousou/hashers/base.py | check_password | sousouindustries/python-libsousou | 0 | python | def check_password(password, encoded, setter=None, preferred='default'):
"\n Returns a boolean of whether the raw password matches the three\n part encoded digest.\n\n If setter is specified, it'll be called when you need to\n regenerate the password.\n "
if ((password is None) or (not is_passwor... | def check_password(password, encoded, setter=None, preferred='default'):
"\n Returns a boolean of whether the raw password matches the three\n part encoded digest.\n\n If setter is specified, it'll be called when you need to\n regenerate the password.\n "
if ((password is None) or (not is_passwor... |
b29a9df1b358a9eb57f9488188cb553986e6b66a1ad726bdedb59a18122b6147 | def get_hasher(algorithm='default'):
"\n Returns an instance of a loaded password hasher.\n If algorithm is 'default', the default hasher will be returned.\n This function will also lazy import hashers specified in your\n settings file if needed.\n "
if hasattr(algorithm, 'algorithm'):
re... | Returns an instance of a loaded password hasher.
If algorithm is 'default', the default hasher will be returned.
This function will also lazy import hashers specified in your
settings file if needed. | libsousou/hashers/base.py | get_hasher | sousouindustries/python-libsousou | 0 | python | def get_hasher(algorithm='default'):
"\n Returns an instance of a loaded password hasher.\n If algorithm is 'default', the default hasher will be returned.\n This function will also lazy import hashers specified in your\n settings file if needed.\n "
if hasattr(algorithm, 'algorithm'):
re... | def get_hasher(algorithm='default'):
"\n Returns an instance of a loaded password hasher.\n If algorithm is 'default', the default hasher will be returned.\n This function will also lazy import hashers specified in your\n settings file if needed.\n "
if hasattr(algorithm, 'algorithm'):
re... |
9c2be2e4dd076db252fd96a5f8ae4f019e41de3f49815bfb75df9eaab422d2fe | def identify_hasher(encoded):
'\n Returns an instance of a loaded password hasher.\n\n Identifies hasher algorithm by examining encoded hash, and calls\n get_hasher() to return hasher. Raises ValueError if\n algorithm cannot be identified, or if hasher is not loaded.\n '
if (((len(encoded) == 32)... | Returns an instance of a loaded password hasher.
Identifies hasher algorithm by examining encoded hash, and calls
get_hasher() to return hasher. Raises ValueError if
algorithm cannot be identified, or if hasher is not loaded. | libsousou/hashers/base.py | identify_hasher | sousouindustries/python-libsousou | 0 | python | def identify_hasher(encoded):
'\n Returns an instance of a loaded password hasher.\n\n Identifies hasher algorithm by examining encoded hash, and calls\n get_hasher() to return hasher. Raises ValueError if\n algorithm cannot be identified, or if hasher is not loaded.\n '
if (((len(encoded) == 32)... | def identify_hasher(encoded):
'\n Returns an instance of a loaded password hasher.\n\n Identifies hasher algorithm by examining encoded hash, and calls\n get_hasher() to return hasher. Raises ValueError if\n algorithm cannot be identified, or if hasher is not loaded.\n '
if (((len(encoded) == 32)... |
97fac01f17a0c8a584d89bfb99ceb248c9d25ddecb38f2aeab3e56cff098e38d | def mask_hash(hash, show=6, char='*'):
'\n Returns the given hash, with only the first ``show`` number shown. The\n rest are masked with ``char`` for security reasons.\n '
masked = hash[:show]
masked += (char * len(hash[show:]))
return masked | Returns the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons. | libsousou/hashers/base.py | mask_hash | sousouindustries/python-libsousou | 0 | python | def mask_hash(hash, show=6, char='*'):
'\n Returns the given hash, with only the first ``show`` number shown. The\n rest are masked with ``char`` for security reasons.\n '
masked = hash[:show]
masked += (char * len(hash[show:]))
return masked | def mask_hash(hash, show=6, char='*'):
'\n Returns the given hash, with only the first ``show`` number shown. The\n rest are masked with ``char`` for security reasons.\n '
masked = hash[:show]
masked += (char * len(hash[show:]))
return masked<|docstring|>Returns the given hash, with only the fi... |
685e821def5ec8f8f539f3817a5bbd1688e819a1b540cf0139aeede1f9cfc4d0 | def constant_time_compare(val1, val2):
'\n Returns True if the two strings are equal, False otherwise.\n\n The time taken is independent of the number of characters that match.\n\n For the sake of simplicity, this function executes in constant time only\n when the two strings have the same length. It sh... | Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings have the same length. It short-circuits when they
have different lengths. | libsousou/hashers/base.py | constant_time_compare | sousouindustries/python-libsousou | 0 | python | def constant_time_compare(val1, val2):
'\n Returns True if the two strings are equal, False otherwise.\n\n The time taken is independent of the number of characters that match.\n\n For the sake of simplicity, this function executes in constant time only\n when the two strings have the same length. It sh... | def constant_time_compare(val1, val2):
'\n Returns True if the two strings are equal, False otherwise.\n\n The time taken is independent of the number of characters that match.\n\n For the sake of simplicity, this function executes in constant time only\n when the two strings have the same length. It sh... |
c09b9b12887b6fac550cce7ebbfa91863b984b9ab9b28a38139f8b0b2b95485f | def _bin_to_long(x):
'\n Convert a binary string into a long integer\n\n This is a clever optimization for fast xor vector math\n '
return int(binascii.hexlify(x), 16) | Convert a binary string into a long integer
This is a clever optimization for fast xor vector math | libsousou/hashers/base.py | _bin_to_long | sousouindustries/python-libsousou | 0 | python | def _bin_to_long(x):
'\n Convert a binary string into a long integer\n\n This is a clever optimization for fast xor vector math\n '
return int(binascii.hexlify(x), 16) | def _bin_to_long(x):
'\n Convert a binary string into a long integer\n\n This is a clever optimization for fast xor vector math\n '
return int(binascii.hexlify(x), 16)<|docstring|>Convert a binary string into a long integer
This is a clever optimization for fast xor vector math<|endoftext|> |
09157b4e121ad563519c070f510cd26574da73d0a0b5c04508a741f359ff356a | def _long_to_bin(x, hex_format_string):
'\n Convert a long integer into a binary string.\n hex_format_string is like "%020x" for padding 10 characters.\n '
return binascii.unhexlify((hex_format_string % x).encode('ascii')) | Convert a long integer into a binary string.
hex_format_string is like "%020x" for padding 10 characters. | libsousou/hashers/base.py | _long_to_bin | sousouindustries/python-libsousou | 0 | python | def _long_to_bin(x, hex_format_string):
'\n Convert a long integer into a binary string.\n hex_format_string is like "%020x" for padding 10 characters.\n '
return binascii.unhexlify((hex_format_string % x).encode('ascii')) | def _long_to_bin(x, hex_format_string):
'\n Convert a long integer into a binary string.\n hex_format_string is like "%020x" for padding 10 characters.\n '
return binascii.unhexlify((hex_format_string % x).encode('ascii'))<|docstring|>Convert a long integer into a binary string.
hex_format_string is li... |
9b9dcdadc7c27432f7d42b87c7fd590bddbfa6c0e7f16ebb1dd26e38f6f1aa05 | def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
'\n Returns a securely generated random string.\n\n The default length of 12 with the a-z, A-Z, 0-9 character set returns\n a 71-bit value. log_2((26+26+10)^12) =~ 71 bits\n '
return ''.... | Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits | libsousou/hashers/base.py | get_random_string | sousouindustries/python-libsousou | 0 | python | def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
'\n Returns a securely generated random string.\n\n The default length of 12 with the a-z, A-Z, 0-9 character set returns\n a 71-bit value. log_2((26+26+10)^12) =~ 71 bits\n '
return .jo... | def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
'\n Returns a securely generated random string.\n\n The default length of 12 with the a-z, A-Z, 0-9 character set returns\n a 71-bit value. log_2((26+26+10)^12) =~ 71 bits\n '
return .jo... |
46c92f09d3c701ae47815a2871bfdd6e72a4d92d1bc5f9a6d394ff3705d21404 | def salt(self):
'\n Generates a cryptographically secure nonce salt in ascii\n '
return get_random_string() | Generates a cryptographically secure nonce salt in ascii | libsousou/hashers/base.py | salt | sousouindustries/python-libsousou | 0 | python | def salt(self):
'\n \n '
return get_random_string() | def salt(self):
'\n \n '
return get_random_string()<|docstring|>Generates a cryptographically secure nonce salt in ascii<|endoftext|> |
3726d840471b2c507b17944f425443c83916707c8ff7f3e209d2190e867432bc | def verify(self, password, encoded):
'\n Checks if the given password is correct\n '
raise NotImplementedError() | Checks if the given password is correct | libsousou/hashers/base.py | verify | sousouindustries/python-libsousou | 0 | python | def verify(self, password, encoded):
'\n \n '
raise NotImplementedError() | def verify(self, password, encoded):
'\n \n '
raise NotImplementedError()<|docstring|>Checks if the given password is correct<|endoftext|> |
6f2ee380bb2e78318ac14f53448b2283c2a23a9ca75e31a75780f0af20643f3e | def encode(self, password, salt):
'\n Creates an encoded database value\n\n The result is normally formatted as "algorithm$salt$hash" and\n must be fewer than 128 characters.\n '
raise NotImplementedError() | Creates an encoded database value
The result is normally formatted as "algorithm$salt$hash" and
must be fewer than 128 characters. | libsousou/hashers/base.py | encode | sousouindustries/python-libsousou | 0 | python | def encode(self, password, salt):
'\n Creates an encoded database value\n\n The result is normally formatted as "algorithm$salt$hash" and\n must be fewer than 128 characters.\n '
raise NotImplementedError() | def encode(self, password, salt):
'\n Creates an encoded database value\n\n The result is normally formatted as "algorithm$salt$hash" and\n must be fewer than 128 characters.\n '
raise NotImplementedError()<|docstring|>Creates an encoded database value
The result is normally formatt... |
bd172d7d34d86f22ed77a841b9c094af04be89055893b7750bcf8fa2bf2d6229 | def safe_summary(self, encoded):
'\n Returns a summary of safe values\n\n The result is a dictionary and will be used where the password field\n must be displayed to construct a safe representation of the password.\n '
raise NotImplementedError() | Returns a summary of safe values
The result is a dictionary and will be used where the password field
must be displayed to construct a safe representation of the password. | libsousou/hashers/base.py | safe_summary | sousouindustries/python-libsousou | 0 | python | def safe_summary(self, encoded):
'\n Returns a summary of safe values\n\n The result is a dictionary and will be used where the password field\n must be displayed to construct a safe representation of the password.\n '
raise NotImplementedError() | def safe_summary(self, encoded):
'\n Returns a summary of safe values\n\n The result is a dictionary and will be used where the password field\n must be displayed to construct a safe representation of the password.\n '
raise NotImplementedError()<|docstring|>Returns a summary of safe... |
f80e45f6e56b3e62a46f0ed47d4e9f1dcd98198d792c72a09951796fedee9e03 | def init(engine):
'\n Call this method before using any of the ORM classes.\n\n :seealso: :meth:olass_client.get_db_session()\n '
DBSession.configure(bind=engine) | Call this method before using any of the ORM classes.
:seealso: :meth:olass_client.get_db_session() | olass/models/base.py | init | ufbmi/olass-client | 0 | python | def init(engine):
'\n Call this method before using any of the ORM classes.\n\n :seealso: :meth:olass_client.get_db_session()\n '
DBSession.configure(bind=engine) | def init(engine):
'\n Call this method before using any of the ORM classes.\n\n :seealso: :meth:olass_client.get_db_session()\n '
DBSession.configure(bind=engine)<|docstring|>Call this method before using any of the ORM classes.
:seealso: :meth:olass_client.get_db_session()<|endoftext|> |
26f3349ad1f43dd87296f4d9c70ff1f5c8a19bf535b55b3d542ee6c281c4f969 | def __repr__(self):
'\n Note: does not print attributes with "_" as prefix\n '
return ('%s(%s)' % (self.__class__.__name__, ', '.join([('%s=%r' % (key, getattr(self, key))) for key in sorted(self.__dict__.keys()) if (not key.startswith('_'))]))) | Note: does not print attributes with "_" as prefix | olass/models/base.py | __repr__ | ufbmi/olass-client | 0 | python | def __repr__(self):
'\n \n '
return ('%s(%s)' % (self.__class__.__name__, ', '.join([('%s=%r' % (key, getattr(self, key))) for key in sorted(self.__dict__.keys()) if (not key.startswith('_'))]))) | def __repr__(self):
'\n \n '
return ('%s(%s)' % (self.__class__.__name__, ', '.join([('%s=%r' % (key, getattr(self, key))) for key in sorted(self.__dict__.keys()) if (not key.startswith('_'))])))<|docstring|>Note: does not print attributes with "_" as prefix<|endoftext|> |
dc883be44b97dd063daafc5e399efa6a21f95f21a14e9fc88db66df9d5dfaccf | def make_declarative_base(self, model_class, metadata=None):
'Creates the declarative base.'
base = declarative.declarative_base(cls=model_class, name='Model', metadata=metadata)
base.query = _QueryProperty(self)
return base | Creates the declarative base. | olass/models/base.py | make_declarative_base | ufbmi/olass-client | 0 | python | def make_declarative_base(self, model_class, metadata=None):
base = declarative.declarative_base(cls=model_class, name='Model', metadata=metadata)
base.query = _QueryProperty(self)
return base | def make_declarative_base(self, model_class, metadata=None):
base = declarative.declarative_base(cls=model_class, name='Model', metadata=metadata)
base.query = _QueryProperty(self)
return base<|docstring|>Creates the declarative base.<|endoftext|> |
d2797e4cdb087516df607714651adf8b218290b45475f39b324d54e56b336cbd | @classmethod
def create_user(cls, username, password):
'Create a user, store and return it.'
new_user = cls(username=username, password=password, nickname=username)
db.session.add(new_user)
db.session.commit()
return new_user | Create a user, store and return it. | server/models/user.py | create_user | TeamDDH/bbk-server | 3 | python | @classmethod
def create_user(cls, username, password):
new_user = cls(username=username, password=password, nickname=username)
db.session.add(new_user)
db.session.commit()
return new_user | @classmethod
def create_user(cls, username, password):
new_user = cls(username=username, password=password, nickname=username)
db.session.add(new_user)
db.session.commit()
return new_user<|docstring|>Create a user, store and return it.<|endoftext|> |
a50c61ab35b19f91a2d4ef63468849aef9179adeacd17b4bd409a6d6ac4dcb60 | def best_fit_transform(A, B):
'\n Calculates the least-squares best-fit transform that maps corresponding points A to B in m spatial dimensions\n Input:\n A: Nxm numpy array of corresponding points\n B: Nxm numpy array of corresponding points\n Returns:\n T: (m+1)x(m+1) homogeneous transform... | Calculates the least-squares best-fit transform that maps corresponding points A to B in m spatial dimensions
Input:
A: Nxm numpy array of corresponding points
B: Nxm numpy array of corresponding points
Returns:
T: (m+1)x(m+1) homogeneous transformation matrix that maps A on to B
R: mxm rotation matrix
t: mx1... | icp.py | best_fit_transform | PythonLidar/PyGraphSLAM | 47 | python | def best_fit_transform(A, B):
'\n Calculates the least-squares best-fit transform that maps corresponding points A to B in m spatial dimensions\n Input:\n A: Nxm numpy array of corresponding points\n B: Nxm numpy array of corresponding points\n Returns:\n T: (m+1)x(m+1) homogeneous transform... | def best_fit_transform(A, B):
'\n Calculates the least-squares best-fit transform that maps corresponding points A to B in m spatial dimensions\n Input:\n A: Nxm numpy array of corresponding points\n B: Nxm numpy array of corresponding points\n Returns:\n T: (m+1)x(m+1) homogeneous transform... |
7d86f92176cd9d6d49eb522ec387eaee480eeffb88725e549d7cf2cba16b0986 | def nearest_neighbor(src, dst):
'\n Find the nearest (Euclidean) neighbor in dst for each point in src\n Input:\n src: Nxm array of points\n dst: Nxm array of points\n Output:\n distances: Euclidean distances of the nearest neighbor\n indices: dst indices of the nearest neighbor... | Find the nearest (Euclidean) neighbor in dst for each point in src
Input:
src: Nxm array of points
dst: Nxm array of points
Output:
distances: Euclidean distances of the nearest neighbor
indices: dst indices of the nearest neighbor | icp.py | nearest_neighbor | PythonLidar/PyGraphSLAM | 47 | python | def nearest_neighbor(src, dst):
'\n Find the nearest (Euclidean) neighbor in dst for each point in src\n Input:\n src: Nxm array of points\n dst: Nxm array of points\n Output:\n distances: Euclidean distances of the nearest neighbor\n indices: dst indices of the nearest neighbor... | def nearest_neighbor(src, dst):
'\n Find the nearest (Euclidean) neighbor in dst for each point in src\n Input:\n src: Nxm array of points\n dst: Nxm array of points\n Output:\n distances: Euclidean distances of the nearest neighbor\n indices: dst indices of the nearest neighbor... |
c76762204c06681c8188cebf904671fafb19a6ad984d37d7d3ae7450bbba5257 | def icp(A, B, init_pose=None, max_iterations=20, tolerance=0.001):
'\n The Iterative Closest Point method: finds best-fit transform that maps points A on to points B\n Input:\n A: Nxm numpy array of source mD points\n B: Nxm numpy array of destination mD point\n init_pose: (m+1)x(m+1) hom... | The Iterative Closest Point method: finds best-fit transform that maps points A on to points B
Input:
A: Nxm numpy array of source mD points
B: Nxm numpy array of destination mD point
init_pose: (m+1)x(m+1) homogeneous transformation
max_iterations: exit algorithm after max_iterations
tolerance: con... | icp.py | icp | PythonLidar/PyGraphSLAM | 47 | python | def icp(A, B, init_pose=None, max_iterations=20, tolerance=0.001):
'\n The Iterative Closest Point method: finds best-fit transform that maps points A on to points B\n Input:\n A: Nxm numpy array of source mD points\n B: Nxm numpy array of destination mD point\n init_pose: (m+1)x(m+1) hom... | def icp(A, B, init_pose=None, max_iterations=20, tolerance=0.001):
'\n The Iterative Closest Point method: finds best-fit transform that maps points A on to points B\n Input:\n A: Nxm numpy array of source mD points\n B: Nxm numpy array of destination mD point\n init_pose: (m+1)x(m+1) hom... |
af06a498db6be24b3c1a79a90f026811762b59741ab69967cc2e8f187d600fc4 | def run_test(self):
'Main test logic'
self.log.info('Test importaddress with label and importprivkey without label.')
self.log.info('Import a watch-only address with a label.')
address = self.nodes[0].getnewaddress()
label = 'Test Label'
self.nodes[1].importaddress(address, label)
test_addre... | Main test logic | test/functional/wallet_import_with_label.py | run_test | Jlemix/bitcoin | 65,371 | python | def run_test(self):
self.log.info('Test importaddress with label and importprivkey without label.')
self.log.info('Import a watch-only address with a label.')
address = self.nodes[0].getnewaddress()
label = 'Test Label'
self.nodes[1].importaddress(address, label)
test_address(self.nodes[1],... | def run_test(self):
self.log.info('Test importaddress with label and importprivkey without label.')
self.log.info('Import a watch-only address with a label.')
address = self.nodes[0].getnewaddress()
label = 'Test Label'
self.nodes[1].importaddress(address, label)
test_address(self.nodes[1],... |
22d3e6a5975671796a55072f4af1525923d7191b7d04e707733faff47e546801 | def setup_position_structure():
' Creates an (average time complexity) O(1) granules access structure.\n Dict with tuple (ca, ce) as key; granule index as value) '
global positions
positions = dict()
for k in range(len(granules)):
ca = granules[k].getCaArity()
ce = granules[k].getCeAr... | Creates an (average time complexity) O(1) granules access structure.
Dict with tuple (ca, ce) as key; granule index as value) | Code/GraphEvoDef/metrics_generation/utilities/JSMAnalysis-JMetrics-d9b7378/jmetrics/scripts/coupling_2D_axis.py | setup_position_structure | vijaybw/graphevodef | 0 | python | def setup_position_structure():
' Creates an (average time complexity) O(1) granules access structure.\n Dict with tuple (ca, ce) as key; granule index as value) '
global positions
positions = dict()
for k in range(len(granules)):
ca = granules[k].getCaArity()
ce = granules[k].getCeAr... | def setup_position_structure():
' Creates an (average time complexity) O(1) granules access structure.\n Dict with tuple (ca, ce) as key; granule index as value) '
global positions
positions = dict()
for k in range(len(granules)):
ca = granules[k].getCaArity()
ce = granules[k].getCeAr... |
1805af71381e3974e3b9e14dbd5338ea130911108cd0c48dc26e33095ea49212 | async def simple_rollout(adv_fn: Callable[([Sequence[N], int], asyncio.Future)], neighbors_fn: Callable[([N], Sequence[N])], probs_fn: Callable[([Sequence[N], np.ndarray], np.ndarray)], start_node: N, depth: int, rng: np.random.Generator):
'Perform a single rollout.'
node = start_node
out = [node]
for s... | Perform a single rollout. | rlo/users/jackd/async_search/async_search.py | simple_rollout | tomjaguarpaw/knossos-ksc | 31 | python | async def simple_rollout(adv_fn: Callable[([Sequence[N], int], asyncio.Future)], neighbors_fn: Callable[([N], Sequence[N])], probs_fn: Callable[([Sequence[N], np.ndarray], np.ndarray)], start_node: N, depth: int, rng: np.random.Generator):
node = start_node
out = [node]
for steps_remaining in range((de... | async def simple_rollout(adv_fn: Callable[([Sequence[N], int], asyncio.Future)], neighbors_fn: Callable[([N], Sequence[N])], probs_fn: Callable[([Sequence[N], np.ndarray], np.ndarray)], start_node: N, depth: int, rng: np.random.Generator):
node = start_node
out = [node]
for steps_remaining in range((de... |
c5aa4fabb22b69b6f6623e04f63f155e7cbd058cec8ec8d749582015f852b1e9 | async def multi_rollout(start_node: N, adv_fn: Callable[([Sequence[N], int], asyncio.Future)], neighbors_fn: Callable[([N], Sequence[N])], probs_fn: Callable[([Sequence[N], np.ndarray], np.ndarray)], depth: int, seed: int, num_rollouts: int):
'Perform multiple rollouts.'
rng = np.random.default_rng(seed)
kw... | Perform multiple rollouts. | rlo/users/jackd/async_search/async_search.py | multi_rollout | tomjaguarpaw/knossos-ksc | 31 | python | async def multi_rollout(start_node: N, adv_fn: Callable[([Sequence[N], int], asyncio.Future)], neighbors_fn: Callable[([N], Sequence[N])], probs_fn: Callable[([Sequence[N], np.ndarray], np.ndarray)], depth: int, seed: int, num_rollouts: int):
rng = np.random.default_rng(seed)
kwargs = dict(start_node=start... | async def multi_rollout(start_node: N, adv_fn: Callable[([Sequence[N], int], asyncio.Future)], neighbors_fn: Callable[([N], Sequence[N])], probs_fn: Callable[([Sequence[N], np.ndarray], np.ndarray)], depth: int, seed: int, num_rollouts: int):
rng = np.random.default_rng(seed)
kwargs = dict(start_node=start... |
67ce16733fe82ba2103067d925f90020c6582715b4b0fc7101e9d92fe5155672 | async def batched_astar_search(start_node: N, adv_fn: Callable[([Sequence[N]], Sequence[asyncio.Future])], neighbors_fn: Callable[([N], Sequence[N])], simulation_depth: int, gnn_budget: int, buffer_size: int) -> AStarResult:
"\n asynchronous port approximating behaviour of `AStarSearcher._search_to_tree`.\n\n ... | asynchronous port approximating behaviour of `AStarSearcher._search_to_tree`.
For reasons currently unknown this doesn't perform -exactly- the same transitions,
but it's the same in spirit.
Compared to AStarSearcher, buffer_size is equivalent to batch_size, though actual
batching is left to the `adv_fn` implementatio... | rlo/users/jackd/async_search/async_search.py | batched_astar_search | tomjaguarpaw/knossos-ksc | 31 | python | async def batched_astar_search(start_node: N, adv_fn: Callable[([Sequence[N]], Sequence[asyncio.Future])], neighbors_fn: Callable[([N], Sequence[N])], simulation_depth: int, gnn_budget: int, buffer_size: int) -> AStarResult:
"\n asynchronous port approximating behaviour of `AStarSearcher._search_to_tree`.\n\n ... | async def batched_astar_search(start_node: N, adv_fn: Callable[([Sequence[N]], Sequence[asyncio.Future])], neighbors_fn: Callable[([N], Sequence[N])], simulation_depth: int, gnn_budget: int, buffer_size: int) -> AStarResult:
"\n asynchronous port approximating behaviour of `AStarSearcher._search_to_tree`.\n\n ... |
e3ef3065dda37bc0c1e17e74ba73c5d14bac000778d3ddf9906c06352f193aa5 | async def continuous_astar_search(start_node: N, neighbors_fn: Callable[([N], Sequence[N])], cost_fn: Callable[([N], float)], adv_fn: Callable[([Sequence[N]], asyncio.Future)], simulation_depth: int, gnn_budget: int, loop=None):
'\n Continuous / asynchronous version of AStar search.\n\n This implementation ma... | Continuous / asynchronous version of AStar search.
This implementation makes requests to `adv_fn` as fast as possible. An
`asyncio.sleep` call is made after each request. | rlo/users/jackd/async_search/async_search.py | continuous_astar_search | tomjaguarpaw/knossos-ksc | 31 | python | async def continuous_astar_search(start_node: N, neighbors_fn: Callable[([N], Sequence[N])], cost_fn: Callable[([N], float)], adv_fn: Callable[([Sequence[N]], asyncio.Future)], simulation_depth: int, gnn_budget: int, loop=None):
'\n Continuous / asynchronous version of AStar search.\n\n This implementation ma... | async def continuous_astar_search(start_node: N, neighbors_fn: Callable[([N], Sequence[N])], cost_fn: Callable[([N], float)], adv_fn: Callable[([Sequence[N]], asyncio.Future)], simulation_depth: int, gnn_budget: int, loop=None):
'\n Continuous / asynchronous version of AStar search.\n\n This implementation ma... |
b7b9fbe607d4c4c22c00bc85059399d99e633f9350cd2fc53412633a11225538 | def compute(self):
'\n implement this to calculate factors normalize to [0,1]\n\n '
self.pre_compute()
self.do_compute()
self.after_compute() | implement this to calculate factors normalize to [0,1] | zvdata/factor.py | compute | freedom6xiaobai/zvt | 1 | python | def compute(self):
'\n \n\n '
self.pre_compute()
self.do_compute()
self.after_compute() | def compute(self):
'\n \n\n '
self.pre_compute()
self.do_compute()
self.after_compute()<|docstring|>implement this to calculate factors normalize to [0,1]<|endoftext|> |
3522ae36c4cfd89442f1934616848e97707c346cea618c5b1a78c46db51bb990 | def on_data_changed(self, data: pd.DataFrame):
'\n overwrite it for computing fast\n\n Parameters\n ----------\n data :\n '
self.compute() | overwrite it for computing fast
Parameters
----------
data : | zvdata/factor.py | on_data_changed | freedom6xiaobai/zvt | 1 | python | def on_data_changed(self, data: pd.DataFrame):
'\n overwrite it for computing fast\n\n Parameters\n ----------\n data :\n '
self.compute() | def on_data_changed(self, data: pd.DataFrame):
'\n overwrite it for computing fast\n\n Parameters\n ----------\n data :\n '
self.compute()<|docstring|>overwrite it for computing fast
Parameters
----------
data :<|endoftext|> |
d96a876ef5ff678b800053bead73ec4b970e09f9bbea61ab2fd657e9882105dd | def on_category_data_added(self, category, added_data: pd.DataFrame):
'\n overwrite it for computing fast\n\n Parameters\n ----------\n category :\n added_data :\n '
self.compute() | overwrite it for computing fast
Parameters
----------
category :
added_data : | zvdata/factor.py | on_category_data_added | freedom6xiaobai/zvt | 1 | python | def on_category_data_added(self, category, added_data: pd.DataFrame):
'\n overwrite it for computing fast\n\n Parameters\n ----------\n category :\n added_data :\n '
self.compute() | def on_category_data_added(self, category, added_data: pd.DataFrame):
'\n overwrite it for computing fast\n\n Parameters\n ----------\n category :\n added_data :\n '
self.compute()<|docstring|>overwrite it for computing fast
Parameters
----------
category :
added_data ... |
8335f09751dba2281a6d08b8f63b3fb96be15108df909d8afafa5fe3527499a4 | def __init__(__self__, resource_name, opts=None, cloudwatch_log_group_arn=None, destination_location_arn=None, name=None, options=None, source_location_arn=None, tags=None, __props__=None, __name__=None, __opts__=None):
'\n Manages an AWS DataSync Task, which represents a configuration for synchronization. S... | Manages an AWS DataSync Task, which represents a configuration for synchronization. Starting an execution of these DataSync Tasks (actually synchronizing files) is performed outside of this resource.
## Example Usage
```python
import pulumi
import pulumi_aws as aws
example = aws.datasync.Task("example",
destinat... | sdk/python/pulumi_aws/datasync/task.py | __init__ | michael-golden/pulumi-aws | 0 | python | def __init__(__self__, resource_name, opts=None, cloudwatch_log_group_arn=None, destination_location_arn=None, name=None, options=None, source_location_arn=None, tags=None, __props__=None, __name__=None, __opts__=None):
'\n Manages an AWS DataSync Task, which represents a configuration for synchronization. S... | def __init__(__self__, resource_name, opts=None, cloudwatch_log_group_arn=None, destination_location_arn=None, name=None, options=None, source_location_arn=None, tags=None, __props__=None, __name__=None, __opts__=None):
'\n Manages an AWS DataSync Task, which represents a configuration for synchronization. S... |
3036b553e9b30b7e17a3fcfc786454ae1bba8cf1252327f77d6f9acad82ba00b | @staticmethod
def get(resource_name, id, opts=None, arn=None, cloudwatch_log_group_arn=None, destination_location_arn=None, name=None, options=None, source_location_arn=None, tags=None):
"\n Get an existing Task resource's state with the given name, id, and optional extra\n properties used to qualify ... | Get an existing Task resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param str id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:p... | sdk/python/pulumi_aws/datasync/task.py | get | michael-golden/pulumi-aws | 0 | python | @staticmethod
def get(resource_name, id, opts=None, arn=None, cloudwatch_log_group_arn=None, destination_location_arn=None, name=None, options=None, source_location_arn=None, tags=None):
"\n Get an existing Task resource's state with the given name, id, and optional extra\n properties used to qualify ... | @staticmethod
def get(resource_name, id, opts=None, arn=None, cloudwatch_log_group_arn=None, destination_location_arn=None, name=None, options=None, source_location_arn=None, tags=None):
"\n Get an existing Task resource's state with the given name, id, and optional extra\n properties used to qualify ... |
dacfac614557691ed1a08c6240000b32475d6874df37516fed5b1cb0051af95b | def get_slit_point(self, R_slit, phi_slit, center_x, center_y, psf_fwhm, num_evaluate):
'\n\n :param R_slit: slit length [arc sec]\n :param phi_slit: angle of slit [radian]\n :param center_x: position of center of slit in x-axis\n :param center_y: position of center of slit in y-axis\n ... | :param R_slit: slit length [arc sec]
:param phi_slit: angle of slit [radian]
:param center_x: position of center of slit in x-axis
:param center_y: position of center of slit in y-axis
:param psf_fwhm: FWHM of (Gaussian) PSF
:param num_evaluate: number of points to be evaluated
:return: | galkin/spectral_apperature.py | get_slit_point | LBJ-Wade/galkin | 1 | python | def get_slit_point(self, R_slit, phi_slit, center_x, center_y, psf_fwhm, num_evaluate):
'\n\n :param R_slit: slit length [arc sec]\n :param phi_slit: angle of slit [radian]\n :param center_x: position of center of slit in x-axis\n :param center_y: position of center of slit in y-axis\n ... | def get_slit_point(self, R_slit, phi_slit, center_x, center_y, psf_fwhm, num_evaluate):
'\n\n :param R_slit: slit length [arc sec]\n :param phi_slit: angle of slit [radian]\n :param center_x: position of center of slit in x-axis\n :param center_y: position of center of slit in y-axis\n ... |
92268484ec5ddccdb2038d8626524c49ba64e66cd4ac8bdf47053576bbf6f98e | def main():
'\n USER CONTROLS\n '
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='Please give a config.json file with training/model/data/param details')
parser.add_argument('--gpu_id', help='Please give a value for gpu id')
parser.add_argument('--model', help='Ple... | USER CONTROLS | realworld_benchmark/main_molecules_gat.py | main | DomInvivo/pna | 0 | python | def main():
'\n \n '
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='Please give a config.json file with training/model/data/param details')
parser.add_argument('--gpu_id', help='Please give a value for gpu id')
parser.add_argument('--model', help='Please give a va... | def main():
'\n \n '
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='Please give a config.json file with training/model/data/param details')
parser.add_argument('--gpu_id', help='Please give a value for gpu id')
parser.add_argument('--model', help='Please give a va... |
60f1777267bd8657f639c641580fd46cb91321a8c3f13568257efafd3f460a84 | def printRostestSummary(result, rostest_results):
'\n Print summary of rostest results to stdout.\n '
global _errors
_errors = result.errors
return rosunit.print_runner_summary(result, rostest_results, runner_name='ROSTEST') | Print summary of rostest results to stdout. | ros_catkin_ws/src/ros_comm/rostest/src/rostest/rostestutil.py | printRostestSummary | letrend/neopixel_fpga | 742 | python | def printRostestSummary(result, rostest_results):
'\n \n '
global _errors
_errors = result.errors
return rosunit.print_runner_summary(result, rostest_results, runner_name='ROSTEST') | def printRostestSummary(result, rostest_results):
'\n \n '
global _errors
_errors = result.errors
return rosunit.print_runner_summary(result, rostest_results, runner_name='ROSTEST')<|docstring|>Print summary of rostest results to stdout.<|endoftext|> |
89e4072c5dc8bc45aa0b382be8932d8916a7c631d3f761527a869ecbfe36c478 | def train(args, model, criterion, optimizer, dataset, collate_fn, epoch_id):
'Model training for one epoch and log the average loss.'
data_gen = dataset.get_data_loader(batch_size=args.batch_size, num_workers=args.num_workers, shuffle=True, collate_fn=collate_fn)
model.train()
list_loss = []
(total_... | Model training for one epoch and log the average loss. | apps/pretrained_compound/info_graph/unsupervised_pretrain.py | train | shiyu1994/PaddleHelix | 454 | python | def train(args, model, criterion, optimizer, dataset, collate_fn, epoch_id):
data_gen = dataset.get_data_loader(batch_size=args.batch_size, num_workers=args.num_workers, shuffle=True, collate_fn=collate_fn)
model.train()
list_loss = []
(total_data, trained_data, batch_id) = (len(dataset), 0, 0)
... | def train(args, model, criterion, optimizer, dataset, collate_fn, epoch_id):
data_gen = dataset.get_data_loader(batch_size=args.batch_size, num_workers=args.num_workers, shuffle=True, collate_fn=collate_fn)
model.train()
list_loss = []
(total_data, trained_data, batch_id) = (len(dataset), 0, 0)
... |
82bb168d6ec2f118c61c6b1c3f1ac112c246cecd2d86032f0cfa11cceb0f58b0 | def save_embedding(args, model, dataset, collate_fn, epoch_id):
'Save the embeddings of all the testing data for multiple classifier evaluation.'
data_gen = dataset.get_data_loader(batch_size=args.batch_size, num_workers=1, shuffle=False, collate_fn=collate_fn)
model.eval()
(graph_emb_lst, graph_label_l... | Save the embeddings of all the testing data for multiple classifier evaluation. | apps/pretrained_compound/info_graph/unsupervised_pretrain.py | save_embedding | shiyu1994/PaddleHelix | 454 | python | def save_embedding(args, model, dataset, collate_fn, epoch_id):
data_gen = dataset.get_data_loader(batch_size=args.batch_size, num_workers=1, shuffle=False, collate_fn=collate_fn)
model.eval()
(graph_emb_lst, graph_label_lst) = ([], [])
for (graphs, labels, valids) in data_gen:
graphs = gra... | def save_embedding(args, model, dataset, collate_fn, epoch_id):
data_gen = dataset.get_data_loader(batch_size=args.batch_size, num_workers=1, shuffle=False, collate_fn=collate_fn)
model.eval()
(graph_emb_lst, graph_label_lst) = ([], [])
for (graphs, labels, valids) in data_gen:
graphs = gra... |
49e440d7d67cc6057bd35c916c4729034f8545d318bf0b3e058515a44fa52bc5 | def parallel_eval(data_queue, pkl_lst):
'The target function to run a multi-classifier evaluation for given embeddings.'
for pkl in pkl_lst:
with open(pkl, 'rb') as f:
data = pickle.load(f)
metrics = eval_on_classifiers(data['emb'], data['y'], search=True)
logging.info('{}: l... | The target function to run a multi-classifier evaluation for given embeddings. | apps/pretrained_compound/info_graph/unsupervised_pretrain.py | parallel_eval | shiyu1994/PaddleHelix | 454 | python | def parallel_eval(data_queue, pkl_lst):
for pkl in pkl_lst:
with open(pkl, 'rb') as f:
data = pickle.load(f)
metrics = eval_on_classifiers(data['emb'], data['y'], search=True)
logging.info('{}: logreg ({:.4f}), svc ({:.4f}), linearsvc ({:.4f}), randomforest ({:.4f})'.format(... | def parallel_eval(data_queue, pkl_lst):
for pkl in pkl_lst:
with open(pkl, 'rb') as f:
data = pickle.load(f)
metrics = eval_on_classifiers(data['emb'], data['y'], search=True)
logging.info('{}: logreg ({:.4f}), svc ({:.4f}), linearsvc ({:.4f}), randomforest ({:.4f})'.format(... |
5268d4c528b3bce934ade94b487b63fdf6f9a9da4741dab8a76662281803a2a2 | def save_eval_metric(res_collect, emb_dir):
'Save the evaluation metrics from parallel evaluation workers.'
base = os.path.basename(emb_dir)
json_file = os.path.join(os.path.dirname(emb_dir), ('%s_eval.json' % base))
keys = list(res_collect.keys())
acc_keys = []
for k in keys:
if (type(r... | Save the evaluation metrics from parallel evaluation workers. | apps/pretrained_compound/info_graph/unsupervised_pretrain.py | save_eval_metric | shiyu1994/PaddleHelix | 454 | python | def save_eval_metric(res_collect, emb_dir):
base = os.path.basename(emb_dir)
json_file = os.path.join(os.path.dirname(emb_dir), ('%s_eval.json' % base))
keys = list(res_collect.keys())
acc_keys = []
for k in keys:
if (type(res_collect[k][0]) is not str):
acc_keys.append(k)
... | def save_eval_metric(res_collect, emb_dir):
base = os.path.basename(emb_dir)
json_file = os.path.join(os.path.dirname(emb_dir), ('%s_eval.json' % base))
keys = list(res_collect.keys())
acc_keys = []
for k in keys:
if (type(res_collect[k][0]) is not str):
acc_keys.append(k)
... |
908e34f68eef3a30348fc5bfaebc546b85aa9c3d3ada7a4210d9d26e46aa24da | def extract_manual_features(tweet):
'\n Takes a not-yet-processed tweet in the form of [word1, word2, ..., wordn]\n Returns a list of manual features adapted from ../resource/2872427.2883062.pdf\n\n - length of comment in tokens\n - average length of word\n - number of periods, question marks, quotes... | Takes a not-yet-processed tweet in the form of [word1, word2, ..., wordn]
Returns a list of manual features adapted from ../resource/2872427.2883062.pdf
- length of comment in tokens
- average length of word
- number of periods, question marks, quotes, and exclamation marks
- number of one letter tokens
- number of ca... | src/generate_feature_matrix.py | extract_manual_features | chenyueg/alw-demo | 0 | python | def extract_manual_features(tweet):
'\n Takes a not-yet-processed tweet in the form of [word1, word2, ..., wordn]\n Returns a list of manual features adapted from ../resource/2872427.2883062.pdf\n\n - length of comment in tokens\n - average length of word\n - number of periods, question marks, quotes... | def extract_manual_features(tweet):
'\n Takes a not-yet-processed tweet in the form of [word1, word2, ..., wordn]\n Returns a list of manual features adapted from ../resource/2872427.2883062.pdf\n\n - length of comment in tokens\n - average length of word\n - number of periods, question marks, quotes... |
1b42c20e907d26e42ec555db0b60d42e3b7ff8aac656e91ea0424816c0810881 | def process_tweets(tweets):
'\n Takes a list of retrieved tweets like ../raw_data/retrieved_tweets.txt\n Returns a list of pre-processed tweets in the format of [number, tweetID, tweet, manual, label]\n '
cleanTweetsWithLabels = []
for each in tweets:
tweet = each.strip('\n').split(' ')
... | Takes a list of retrieved tweets like ../raw_data/retrieved_tweets.txt
Returns a list of pre-processed tweets in the format of [number, tweetID, tweet, manual, label] | src/generate_feature_matrix.py | process_tweets | chenyueg/alw-demo | 0 | python | def process_tweets(tweets):
'\n Takes a list of retrieved tweets like ../raw_data/retrieved_tweets.txt\n Returns a list of pre-processed tweets in the format of [number, tweetID, tweet, manual, label]\n '
cleanTweetsWithLabels = []
for each in tweets:
tweet = each.strip('\n').split(' ')
... | def process_tweets(tweets):
'\n Takes a list of retrieved tweets like ../raw_data/retrieved_tweets.txt\n Returns a list of pre-processed tweets in the format of [number, tweetID, tweet, manual, label]\n '
cleanTweetsWithLabels = []
for each in tweets:
tweet = each.strip('\n').split(' ')
... |
d0fd2e76665b8b22943ee20da2f314b95484c9fce8eeb5667736b029f5a1b610 | def process_words(words):
'\n Takes a file with each line being one word\n Returns a list of lowercase word\n '
wordList = []
for word in words:
wordList.append(word.strip().lower())
return wordList | Takes a file with each line being one word
Returns a list of lowercase word | src/generate_feature_matrix.py | process_words | chenyueg/alw-demo | 0 | python | def process_words(words):
'\n Takes a file with each line being one word\n Returns a list of lowercase word\n '
wordList = []
for word in words:
wordList.append(word.strip().lower())
return wordList | def process_words(words):
'\n Takes a file with each line being one word\n Returns a list of lowercase word\n '
wordList = []
for word in words:
wordList.append(word.strip().lower())
return wordList<|docstring|>Takes a file with each line being one word
Returns a list of lowercase word<... |
85190d05c13d14620a7ff478ad0f837f0f75b7714b63794b4c5a02e0bcaf31c7 | def generate_matrix(tweets, words):
'\n Takes a list of processed tweets\n Returns a feature matrix\n See detailed comments below\n '
wordsLentgh = len(words)
featureMatrix = []
for tweet in tweets:
featureVector = ([0] * wordsLentgh)
for i in range(wordsLentgh):
... | Takes a list of processed tweets
Returns a feature matrix
See detailed comments below | src/generate_feature_matrix.py | generate_matrix | chenyueg/alw-demo | 0 | python | def generate_matrix(tweets, words):
'\n Takes a list of processed tweets\n Returns a feature matrix\n See detailed comments below\n '
wordsLentgh = len(words)
featureMatrix = []
for tweet in tweets:
featureVector = ([0] * wordsLentgh)
for i in range(wordsLentgh):
... | def generate_matrix(tweets, words):
'\n Takes a list of processed tweets\n Returns a feature matrix\n See detailed comments below\n '
wordsLentgh = len(words)
featureMatrix = []
for tweet in tweets:
featureVector = ([0] * wordsLentgh)
for i in range(wordsLentgh):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.