id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
245,400
|
GemHQ/round-py
|
round/accounts.py
|
Accounts.create
|
def create(self, name, network):
"""Create a new Account object and add it to this Accounts collection.
Args:
name (str): Account name
network (str): Type of cryptocurrency. Can be one of, 'bitcoin', '
bitcoin_testnet', 'litecoin', 'dogecoin'.
Returns: The new round.Account
"""
if not network in SUPPORTED_NETWORKS:
raise ValueError('Network not valid!')
account = self.wrap(self.resource.create(dict(name=name,
network=network)))
self.add(account)
return account
|
python
|
def create(self, name, network):
"""Create a new Account object and add it to this Accounts collection.
Args:
name (str): Account name
network (str): Type of cryptocurrency. Can be one of, 'bitcoin', '
bitcoin_testnet', 'litecoin', 'dogecoin'.
Returns: The new round.Account
"""
if not network in SUPPORTED_NETWORKS:
raise ValueError('Network not valid!')
account = self.wrap(self.resource.create(dict(name=name,
network=network)))
self.add(account)
return account
|
[
"def",
"create",
"(",
"self",
",",
"name",
",",
"network",
")",
":",
"if",
"not",
"network",
"in",
"SUPPORTED_NETWORKS",
":",
"raise",
"ValueError",
"(",
"'Network not valid!'",
")",
"account",
"=",
"self",
".",
"wrap",
"(",
"self",
".",
"resource",
".",
"create",
"(",
"dict",
"(",
"name",
"=",
"name",
",",
"network",
"=",
"network",
")",
")",
")",
"self",
".",
"add",
"(",
"account",
")",
"return",
"account"
] |
Create a new Account object and add it to this Accounts collection.
Args:
name (str): Account name
network (str): Type of cryptocurrency. Can be one of, 'bitcoin', '
bitcoin_testnet', 'litecoin', 'dogecoin'.
Returns: The new round.Account
|
[
"Create",
"a",
"new",
"Account",
"object",
"and",
"add",
"it",
"to",
"this",
"Accounts",
"collection",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/accounts.py#L50-L65
|
245,401
|
GemHQ/round-py
|
round/accounts.py
|
Account.update
|
def update(self, **kwargs):
"""Update the Account resource with specified content.
Args:
name (str): Human-readable name for the account
Returns: the updated Account object.
"""
return self.__class__(self.resource.update(kwargs),
self.client,
wallet=self.wallet)
|
python
|
def update(self, **kwargs):
"""Update the Account resource with specified content.
Args:
name (str): Human-readable name for the account
Returns: the updated Account object.
"""
return self.__class__(self.resource.update(kwargs),
self.client,
wallet=self.wallet)
|
[
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"resource",
".",
"update",
"(",
"kwargs",
")",
",",
"self",
".",
"client",
",",
"wallet",
"=",
"self",
".",
"wallet",
")"
] |
Update the Account resource with specified content.
Args:
name (str): Human-readable name for the account
Returns: the updated Account object.
|
[
"Update",
"the",
"Account",
"resource",
"with",
"specified",
"content",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/accounts.py#L89-L99
|
245,402
|
GemHQ/round-py
|
round/accounts.py
|
Account.pay
|
def pay(self, payees, change_account=None, utxo_confirmations=6,
mfa_token=None, redirect_uri=None):
"""Create, verify, and sign a new Transaction.
If this Account is owned by a User object, the user must be redirected to
a URL (`mfa_uri`) returned by this call to input their MFA token. After
they complete that step, the Transaction will be approved and published
to the bitcoin network. If a `redirect_uri` is provided in this call, the
user will be redirected to that uri after they complete the MFA challenge
so it's a good idea to have an endpoint in your app (or custom scheme on
mobile) that can provide the user a seamless flow for returning to your
application. If they have not configured a TOTP MFA application (e.g.
Google Authenticator), then an SMS will be sent to their phone number
with their token.
If this Account is owned by an Application, the `mfa_token` can be
included in this call and the Transaction will be automatically approved
and published to the blockchain.
Args:
payees (list of dict): list of outputs in the form:
[{'amount': 10000(satoshis),
'address':'validbtcaddress'}, ...]
change_account (str or Account): if supplied, this account will
be used to generate a change address in the event that a change
output is required. This account must be owned by the same Wallet.
utxo_confirmations (int, optional): Required confirmations for UTXO
selection ( > 0)
mfa_token (str/function, optional): TOTP token for the Application
owning this Account's wallet OR a callable/function which will
generate such a token. The latter is suggested
(e.g. application.get_mfa) as otherwise, the token might be
invalidated by the time tx.create and tx.update complete (before
the tx.approve call which actually requires the mfa_token).
redirect_uri (str, optional): URI to redirect a user to after they
input an mfa token on the page referenced by the `mfa_uri` returned
by this function.
Returns: An "unapproved" Transaction with an `mfa_uri` attribute to route
the user to the MFA confirmation page -- if called with Gem-Device
authentication.
An "unconfirmed" Transaction -- if called with Gem-Application auth
(and an `mfa_token` was supplied).
"""
# Check that wallet is unlocked
if self.wallet.is_locked():
raise DecryptionError("This wallet must be unlocked with "
"wallet.unlock(passphrase)")
# First create the unsigned tx.
content = dict(payees=payees,
utxo_confirmations=utxo_confirmations,
remainder_account=self.resource.attributes['key'],
network=self.network)
if change_account: content['change_account'] = \
self.wallet._get_account_attr(change_account)
try:
unsigned = self.resource.transactions().create(content)
except ResponseError as e:
if "cannot cover" in e.message:
raise BalanceError(e.message)
raise e
# Sign the tx with the primary private key.
coinoptx = CoinopTx(data=unsigned.attributes)
signatures = self.wallet.signatures(coinoptx)
# Update the tx with the signatures.
transaction = dict(signatures=dict(inputs=signatures,
transaction_hash=coinoptx.hash))
if redirect_uri:
transaction['redirect_uri'] = redirect_uri
signed = Transaction(unsigned.update(transaction), self.client)
# If this is an Application wallet, approve the transaction.
if mfa_token and self.wallet.application:
try:
return Transaction(signed.with_mfa(mfa_token).approve(),
self.client)
except Exception as e:
signed = signed.cancel()
logger.debug(e.message)
logger.debug("If you are having trouble with MFA tokens, make "
"sure your system time is accurate with `date -u`!")
# Otherwise return the unapproved tx (now redirect the user to the
# `mfa_uri` attribute to approve!)
return signed
|
python
|
def pay(self, payees, change_account=None, utxo_confirmations=6,
mfa_token=None, redirect_uri=None):
"""Create, verify, and sign a new Transaction.
If this Account is owned by a User object, the user must be redirected to
a URL (`mfa_uri`) returned by this call to input their MFA token. After
they complete that step, the Transaction will be approved and published
to the bitcoin network. If a `redirect_uri` is provided in this call, the
user will be redirected to that uri after they complete the MFA challenge
so it's a good idea to have an endpoint in your app (or custom scheme on
mobile) that can provide the user a seamless flow for returning to your
application. If they have not configured a TOTP MFA application (e.g.
Google Authenticator), then an SMS will be sent to their phone number
with their token.
If this Account is owned by an Application, the `mfa_token` can be
included in this call and the Transaction will be automatically approved
and published to the blockchain.
Args:
payees (list of dict): list of outputs in the form:
[{'amount': 10000(satoshis),
'address':'validbtcaddress'}, ...]
change_account (str or Account): if supplied, this account will
be used to generate a change address in the event that a change
output is required. This account must be owned by the same Wallet.
utxo_confirmations (int, optional): Required confirmations for UTXO
selection ( > 0)
mfa_token (str/function, optional): TOTP token for the Application
owning this Account's wallet OR a callable/function which will
generate such a token. The latter is suggested
(e.g. application.get_mfa) as otherwise, the token might be
invalidated by the time tx.create and tx.update complete (before
the tx.approve call which actually requires the mfa_token).
redirect_uri (str, optional): URI to redirect a user to after they
input an mfa token on the page referenced by the `mfa_uri` returned
by this function.
Returns: An "unapproved" Transaction with an `mfa_uri` attribute to route
the user to the MFA confirmation page -- if called with Gem-Device
authentication.
An "unconfirmed" Transaction -- if called with Gem-Application auth
(and an `mfa_token` was supplied).
"""
# Check that wallet is unlocked
if self.wallet.is_locked():
raise DecryptionError("This wallet must be unlocked with "
"wallet.unlock(passphrase)")
# First create the unsigned tx.
content = dict(payees=payees,
utxo_confirmations=utxo_confirmations,
remainder_account=self.resource.attributes['key'],
network=self.network)
if change_account: content['change_account'] = \
self.wallet._get_account_attr(change_account)
try:
unsigned = self.resource.transactions().create(content)
except ResponseError as e:
if "cannot cover" in e.message:
raise BalanceError(e.message)
raise e
# Sign the tx with the primary private key.
coinoptx = CoinopTx(data=unsigned.attributes)
signatures = self.wallet.signatures(coinoptx)
# Update the tx with the signatures.
transaction = dict(signatures=dict(inputs=signatures,
transaction_hash=coinoptx.hash))
if redirect_uri:
transaction['redirect_uri'] = redirect_uri
signed = Transaction(unsigned.update(transaction), self.client)
# If this is an Application wallet, approve the transaction.
if mfa_token and self.wallet.application:
try:
return Transaction(signed.with_mfa(mfa_token).approve(),
self.client)
except Exception as e:
signed = signed.cancel()
logger.debug(e.message)
logger.debug("If you are having trouble with MFA tokens, make "
"sure your system time is accurate with `date -u`!")
# Otherwise return the unapproved tx (now redirect the user to the
# `mfa_uri` attribute to approve!)
return signed
|
[
"def",
"pay",
"(",
"self",
",",
"payees",
",",
"change_account",
"=",
"None",
",",
"utxo_confirmations",
"=",
"6",
",",
"mfa_token",
"=",
"None",
",",
"redirect_uri",
"=",
"None",
")",
":",
"# Check that wallet is unlocked",
"if",
"self",
".",
"wallet",
".",
"is_locked",
"(",
")",
":",
"raise",
"DecryptionError",
"(",
"\"This wallet must be unlocked with \"",
"\"wallet.unlock(passphrase)\"",
")",
"# First create the unsigned tx.",
"content",
"=",
"dict",
"(",
"payees",
"=",
"payees",
",",
"utxo_confirmations",
"=",
"utxo_confirmations",
",",
"remainder_account",
"=",
"self",
".",
"resource",
".",
"attributes",
"[",
"'key'",
"]",
",",
"network",
"=",
"self",
".",
"network",
")",
"if",
"change_account",
":",
"content",
"[",
"'change_account'",
"]",
"=",
"self",
".",
"wallet",
".",
"_get_account_attr",
"(",
"change_account",
")",
"try",
":",
"unsigned",
"=",
"self",
".",
"resource",
".",
"transactions",
"(",
")",
".",
"create",
"(",
"content",
")",
"except",
"ResponseError",
"as",
"e",
":",
"if",
"\"cannot cover\"",
"in",
"e",
".",
"message",
":",
"raise",
"BalanceError",
"(",
"e",
".",
"message",
")",
"raise",
"e",
"# Sign the tx with the primary private key.",
"coinoptx",
"=",
"CoinopTx",
"(",
"data",
"=",
"unsigned",
".",
"attributes",
")",
"signatures",
"=",
"self",
".",
"wallet",
".",
"signatures",
"(",
"coinoptx",
")",
"# Update the tx with the signatures.",
"transaction",
"=",
"dict",
"(",
"signatures",
"=",
"dict",
"(",
"inputs",
"=",
"signatures",
",",
"transaction_hash",
"=",
"coinoptx",
".",
"hash",
")",
")",
"if",
"redirect_uri",
":",
"transaction",
"[",
"'redirect_uri'",
"]",
"=",
"redirect_uri",
"signed",
"=",
"Transaction",
"(",
"unsigned",
".",
"update",
"(",
"transaction",
")",
",",
"self",
".",
"client",
")",
"# If this is an Application wallet, approve the transaction.",
"if",
"mfa_token",
"and",
"self",
".",
"wallet",
".",
"application",
":",
"try",
":",
"return",
"Transaction",
"(",
"signed",
".",
"with_mfa",
"(",
"mfa_token",
")",
".",
"approve",
"(",
")",
",",
"self",
".",
"client",
")",
"except",
"Exception",
"as",
"e",
":",
"signed",
"=",
"signed",
".",
"cancel",
"(",
")",
"logger",
".",
"debug",
"(",
"e",
".",
"message",
")",
"logger",
".",
"debug",
"(",
"\"If you are having trouble with MFA tokens, make \"",
"\"sure your system time is accurate with `date -u`!\"",
")",
"# Otherwise return the unapproved tx (now redirect the user to the",
"# `mfa_uri` attribute to approve!)",
"return",
"signed"
] |
Create, verify, and sign a new Transaction.
If this Account is owned by a User object, the user must be redirected to
a URL (`mfa_uri`) returned by this call to input their MFA token. After
they complete that step, the Transaction will be approved and published
to the bitcoin network. If a `redirect_uri` is provided in this call, the
user will be redirected to that uri after they complete the MFA challenge
so it's a good idea to have an endpoint in your app (or custom scheme on
mobile) that can provide the user a seamless flow for returning to your
application. If they have not configured a TOTP MFA application (e.g.
Google Authenticator), then an SMS will be sent to their phone number
with their token.
If this Account is owned by an Application, the `mfa_token` can be
included in this call and the Transaction will be automatically approved
and published to the blockchain.
Args:
payees (list of dict): list of outputs in the form:
[{'amount': 10000(satoshis),
'address':'validbtcaddress'}, ...]
change_account (str or Account): if supplied, this account will
be used to generate a change address in the event that a change
output is required. This account must be owned by the same Wallet.
utxo_confirmations (int, optional): Required confirmations for UTXO
selection ( > 0)
mfa_token (str/function, optional): TOTP token for the Application
owning this Account's wallet OR a callable/function which will
generate such a token. The latter is suggested
(e.g. application.get_mfa) as otherwise, the token might be
invalidated by the time tx.create and tx.update complete (before
the tx.approve call which actually requires the mfa_token).
redirect_uri (str, optional): URI to redirect a user to after they
input an mfa token on the page referenced by the `mfa_uri` returned
by this function.
Returns: An "unapproved" Transaction with an `mfa_uri` attribute to route
the user to the MFA confirmation page -- if called with Gem-Device
authentication.
An "unconfirmed" Transaction -- if called with Gem-Application auth
(and an `mfa_token` was supplied).
|
[
"Create",
"verify",
"and",
"sign",
"a",
"new",
"Transaction",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/accounts.py#L101-L191
|
245,403
|
GemHQ/round-py
|
round/accounts.py
|
Account.get_addresses
|
def get_addresses(self, fetch=False):
"""Return the Account's addresses object, populating it if fetch is True."""
return Addresses(self.resource.addresses, self.client, populate=fetch)
|
python
|
def get_addresses(self, fetch=False):
"""Return the Account's addresses object, populating it if fetch is True."""
return Addresses(self.resource.addresses, self.client, populate=fetch)
|
[
"def",
"get_addresses",
"(",
"self",
",",
"fetch",
"=",
"False",
")",
":",
"return",
"Addresses",
"(",
"self",
".",
"resource",
".",
"addresses",
",",
"self",
".",
"client",
",",
"populate",
"=",
"fetch",
")"
] |
Return the Account's addresses object, populating it if fetch is True.
|
[
"Return",
"the",
"Account",
"s",
"addresses",
"object",
"populating",
"it",
"if",
"fetch",
"is",
"True",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/accounts.py#L251-L253
|
245,404
|
GemHQ/round-py
|
round/accounts.py
|
Account.get_netki_names
|
def get_netki_names(self, fetch=False):
"""Return the Account's NetkiNames object, populating it if fetch is True."""
return NetkiNames(self.resource.netki_names, self.client, populate=fetch)
|
python
|
def get_netki_names(self, fetch=False):
"""Return the Account's NetkiNames object, populating it if fetch is True."""
return NetkiNames(self.resource.netki_names, self.client, populate=fetch)
|
[
"def",
"get_netki_names",
"(",
"self",
",",
"fetch",
"=",
"False",
")",
":",
"return",
"NetkiNames",
"(",
"self",
".",
"resource",
".",
"netki_names",
",",
"self",
".",
"client",
",",
"populate",
"=",
"fetch",
")"
] |
Return the Account's NetkiNames object, populating it if fetch is True.
|
[
"Return",
"the",
"Account",
"s",
"NetkiNames",
"object",
"populating",
"it",
"if",
"fetch",
"is",
"True",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/accounts.py#L261-L263
|
245,405
|
tonyseek/html5lib-truncation
|
html5lib_truncation/shortcuts.py
|
truncate_html
|
def truncate_html(html, *args, **kwargs):
"""Truncates HTML string.
:param html: The HTML string or parsed element tree (with
:func:`html5lib.parse`).
:param kwargs: Similar with :class:`.filters.TruncationFilter`.
:return: The truncated HTML string.
"""
if hasattr(html, 'getchildren'):
etree = html
else:
etree = html5lib.parse(html)
walker = html5lib.getTreeWalker('etree')
stream = walker(etree)
stream = TruncationFilter(stream, *args, **kwargs)
serializer = html5lib.serializer.HTMLSerializer()
serialized = serializer.serialize(stream)
return u''.join(serialized).strip()
|
python
|
def truncate_html(html, *args, **kwargs):
"""Truncates HTML string.
:param html: The HTML string or parsed element tree (with
:func:`html5lib.parse`).
:param kwargs: Similar with :class:`.filters.TruncationFilter`.
:return: The truncated HTML string.
"""
if hasattr(html, 'getchildren'):
etree = html
else:
etree = html5lib.parse(html)
walker = html5lib.getTreeWalker('etree')
stream = walker(etree)
stream = TruncationFilter(stream, *args, **kwargs)
serializer = html5lib.serializer.HTMLSerializer()
serialized = serializer.serialize(stream)
return u''.join(serialized).strip()
|
[
"def",
"truncate_html",
"(",
"html",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"html",
",",
"'getchildren'",
")",
":",
"etree",
"=",
"html",
"else",
":",
"etree",
"=",
"html5lib",
".",
"parse",
"(",
"html",
")",
"walker",
"=",
"html5lib",
".",
"getTreeWalker",
"(",
"'etree'",
")",
"stream",
"=",
"walker",
"(",
"etree",
")",
"stream",
"=",
"TruncationFilter",
"(",
"stream",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"serializer",
"=",
"html5lib",
".",
"serializer",
".",
"HTMLSerializer",
"(",
")",
"serialized",
"=",
"serializer",
".",
"serialize",
"(",
"stream",
")",
"return",
"u''",
".",
"join",
"(",
"serialized",
")",
".",
"strip",
"(",
")"
] |
Truncates HTML string.
:param html: The HTML string or parsed element tree (with
:func:`html5lib.parse`).
:param kwargs: Similar with :class:`.filters.TruncationFilter`.
:return: The truncated HTML string.
|
[
"Truncates",
"HTML",
"string",
"."
] |
b5551e345e583d04dbdf6b97dc2a43a266eec8d6
|
https://github.com/tonyseek/html5lib-truncation/blob/b5551e345e583d04dbdf6b97dc2a43a266eec8d6/html5lib_truncation/shortcuts.py#L8-L30
|
245,406
|
s-m-i-t-a/flask-musers
|
flask_musers/models.py
|
is_allowed
|
def is_allowed(func):
"""Check user password, when is correct, then run decorated function.
:returns: decorated function
"""
@wraps(func)
def _is_allowed(user, *args, **kwargs):
password = kwargs.pop('password', None)
if user.check_password(password):
return func(user, *args, **kwargs)
else:
raise NotAllowedError()
# add password parameter to function signature
sig = inspect.signature(func)
parms = list(sig.parameters.values())
parms.append(inspect.Parameter('password',
inspect.Parameter.KEYWORD_ONLY,
default=None))
_is_allowed.__signature__ = sig.replace(parameters=parms)
return _is_allowed
|
python
|
def is_allowed(func):
"""Check user password, when is correct, then run decorated function.
:returns: decorated function
"""
@wraps(func)
def _is_allowed(user, *args, **kwargs):
password = kwargs.pop('password', None)
if user.check_password(password):
return func(user, *args, **kwargs)
else:
raise NotAllowedError()
# add password parameter to function signature
sig = inspect.signature(func)
parms = list(sig.parameters.values())
parms.append(inspect.Parameter('password',
inspect.Parameter.KEYWORD_ONLY,
default=None))
_is_allowed.__signature__ = sig.replace(parameters=parms)
return _is_allowed
|
[
"def",
"is_allowed",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"_is_allowed",
"(",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"password",
"=",
"kwargs",
".",
"pop",
"(",
"'password'",
",",
"None",
")",
"if",
"user",
".",
"check_password",
"(",
"password",
")",
":",
"return",
"func",
"(",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"raise",
"NotAllowedError",
"(",
")",
"# add password parameter to function signature",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"parms",
"=",
"list",
"(",
"sig",
".",
"parameters",
".",
"values",
"(",
")",
")",
"parms",
".",
"append",
"(",
"inspect",
".",
"Parameter",
"(",
"'password'",
",",
"inspect",
".",
"Parameter",
".",
"KEYWORD_ONLY",
",",
"default",
"=",
"None",
")",
")",
"_is_allowed",
".",
"__signature__",
"=",
"sig",
".",
"replace",
"(",
"parameters",
"=",
"parms",
")",
"return",
"_is_allowed"
] |
Check user password, when is correct, then run decorated function.
:returns: decorated function
|
[
"Check",
"user",
"password",
"when",
"is",
"correct",
"then",
"run",
"decorated",
"function",
"."
] |
6becb5de4e8908f878ce173560c3cab4b297b0e0
|
https://github.com/s-m-i-t-a/flask-musers/blob/6becb5de4e8908f878ce173560c3cab4b297b0e0/flask_musers/models.py#L78-L100
|
245,407
|
dossier/dossier.label
|
dossier/label/run.py
|
App.do_get
|
def do_get(self, args):
'''Get labels directly connected to a content item.'''
for label in self.label_store.directly_connected(args.content_id):
if args.value is None or label.value.value == args.value:
self.stdout.write('{0}\n'.format(label))
|
python
|
def do_get(self, args):
'''Get labels directly connected to a content item.'''
for label in self.label_store.directly_connected(args.content_id):
if args.value is None or label.value.value == args.value:
self.stdout.write('{0}\n'.format(label))
|
[
"def",
"do_get",
"(",
"self",
",",
"args",
")",
":",
"for",
"label",
"in",
"self",
".",
"label_store",
".",
"directly_connected",
"(",
"args",
".",
"content_id",
")",
":",
"if",
"args",
".",
"value",
"is",
"None",
"or",
"label",
".",
"value",
".",
"value",
"==",
"args",
".",
"value",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'{0}\\n'",
".",
"format",
"(",
"label",
")",
")"
] |
Get labels directly connected to a content item.
|
[
"Get",
"labels",
"directly",
"connected",
"to",
"a",
"content",
"item",
"."
] |
d445e56b02ffd91ad46b0872cfbff62b9afef7ec
|
https://github.com/dossier/dossier.label/blob/d445e56b02ffd91ad46b0872cfbff62b9afef7ec/dossier/label/run.py#L155-L159
|
245,408
|
dossier/dossier.label
|
dossier/label/run.py
|
App.do_connected
|
def do_connected(self, args):
'''Find a connected component from positive labels on an item.'''
connected = self.label_store.connected_component(args.content_id)
for label in connected:
self.stdout.write('{0}\n'.format(label))
|
python
|
def do_connected(self, args):
'''Find a connected component from positive labels on an item.'''
connected = self.label_store.connected_component(args.content_id)
for label in connected:
self.stdout.write('{0}\n'.format(label))
|
[
"def",
"do_connected",
"(",
"self",
",",
"args",
")",
":",
"connected",
"=",
"self",
".",
"label_store",
".",
"connected_component",
"(",
"args",
".",
"content_id",
")",
"for",
"label",
"in",
"connected",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'{0}\\n'",
".",
"format",
"(",
"label",
")",
")"
] |
Find a connected component from positive labels on an item.
|
[
"Find",
"a",
"connected",
"component",
"from",
"positive",
"labels",
"on",
"an",
"item",
"."
] |
d445e56b02ffd91ad46b0872cfbff62b9afef7ec
|
https://github.com/dossier/dossier.label/blob/d445e56b02ffd91ad46b0872cfbff62b9afef7ec/dossier/label/run.py#L165-L169
|
245,409
|
IntegralDefense/vxstreamlib
|
bin/vxstreamlib.py
|
VxStreamSubmissionManager.wait
|
def wait(self):
"""Waits for all submitted jobs to complete."""
logging.info("waiting for {} jobs to complete".format(len(self.submissions)))
while not self.shutdown:
time.sleep(1)
|
python
|
def wait(self):
"""Waits for all submitted jobs to complete."""
logging.info("waiting for {} jobs to complete".format(len(self.submissions)))
while not self.shutdown:
time.sleep(1)
|
[
"def",
"wait",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"\"waiting for {} jobs to complete\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"submissions",
")",
")",
")",
"while",
"not",
"self",
".",
"shutdown",
":",
"time",
".",
"sleep",
"(",
"1",
")"
] |
Waits for all submitted jobs to complete.
|
[
"Waits",
"for",
"all",
"submitted",
"jobs",
"to",
"complete",
"."
] |
cd82e3975215085cf929c5976f37083b9a3ac869
|
https://github.com/IntegralDefense/vxstreamlib/blob/cd82e3975215085cf929c5976f37083b9a3ac869/bin/vxstreamlib.py#L185-L189
|
245,410
|
IntegralDefense/vxstreamlib
|
bin/vxstreamlib.py
|
VxStreamServer.download_dropped_files
|
def download_dropped_files(self, sha256, environment_id, target_dir):
"""Downloads the dropped files for this sample into target_dir. Returns the list of files extracted."""
download_url = '{}/api/sample-dropped-files/{}?environmentId={}&apikey={}&secret={}'.format(
self.url,
sha256,
environment_id,
self.api_key,
self.secret)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
logging.info("downloading dropped files from {}".format(download_url))
result = requests.get(download_url, verify=False, headers=VXSTREAM_HEADERS, proxies=self.proxies) # XXX
if result.status_code != 200:
logging.error("got result {} from vxstream for {}: {}".format(result.status_code, download_url, result.reason))
return None
# put what we download into a temporary directory
temp_dir = tempfile.mkdtemp()
try:
# all dropped files come in a zip file
compressed_path = os.path.join(temp_dir, 'download.zip')
# write zip file to disk
with open(compressed_path, 'wb') as fp:
for block in result.iter_content(io.DEFAULT_BUFFER_SIZE):
fp.write(block)
# unzip without paths
p = Popen(['7z', 'e', '-y', '-o{}'.format(target_dir), compressed_path], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
try:
os.remove(compressed_path)
except Exception as e:
logging.error("unable to delete {}: {}".format(compressed_path, e))
# list gz files in drop_path
file_list = [os.path.join(target_dir, f) for f in os.listdir(target_dir) if f.endswith('.gz')]
result = []
for compressed_path in file_list:
# there are some other files in here sometimes that we'll ignore
# we just want the dropped file
if '.DROPPED.' not in compressed_path:
continue
DROPPED_FILE_REGEX = re.compile(r'^(.+?)\.[0-9]+\.DROPPED\.gz')
# the file paths look like this
# dropped/78QC7UOHAWCI47906LWH.temp.4212842214.DROPPED.gZ
m = DROPPED_FILE_REGEX.match(os.path.basename(compressed_path))
if not m:
logging.error("could not extract file name from {}".format(compressed_path))
continue
target_path = os.path.join(target_dir, m.group(1))
result.append(target_path)
with gzip.open(compressed_path) as fp:
logging.debug("decompressing {}".format(compressed_path))
with open(target_path, 'wb') as dest_fp:
while True:
data = fp.read(io.DEFAULT_BUFFER_SIZE)
if data == b'':
break
dest_fp.write(data)
os.remove(compressed_path)
return result
finally:
try:
if temp_dir:
shutil.rmtree(temp_dir)
except Exception as e:
logging.error("unable to delete temporary directory {}: {}".format(temp_dir, e))
|
python
|
def download_dropped_files(self, sha256, environment_id, target_dir):
"""Downloads the dropped files for this sample into target_dir. Returns the list of files extracted."""
download_url = '{}/api/sample-dropped-files/{}?environmentId={}&apikey={}&secret={}'.format(
self.url,
sha256,
environment_id,
self.api_key,
self.secret)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
logging.info("downloading dropped files from {}".format(download_url))
result = requests.get(download_url, verify=False, headers=VXSTREAM_HEADERS, proxies=self.proxies) # XXX
if result.status_code != 200:
logging.error("got result {} from vxstream for {}: {}".format(result.status_code, download_url, result.reason))
return None
# put what we download into a temporary directory
temp_dir = tempfile.mkdtemp()
try:
# all dropped files come in a zip file
compressed_path = os.path.join(temp_dir, 'download.zip')
# write zip file to disk
with open(compressed_path, 'wb') as fp:
for block in result.iter_content(io.DEFAULT_BUFFER_SIZE):
fp.write(block)
# unzip without paths
p = Popen(['7z', 'e', '-y', '-o{}'.format(target_dir), compressed_path], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
try:
os.remove(compressed_path)
except Exception as e:
logging.error("unable to delete {}: {}".format(compressed_path, e))
# list gz files in drop_path
file_list = [os.path.join(target_dir, f) for f in os.listdir(target_dir) if f.endswith('.gz')]
result = []
for compressed_path in file_list:
# there are some other files in here sometimes that we'll ignore
# we just want the dropped file
if '.DROPPED.' not in compressed_path:
continue
DROPPED_FILE_REGEX = re.compile(r'^(.+?)\.[0-9]+\.DROPPED\.gz')
# the file paths look like this
# dropped/78QC7UOHAWCI47906LWH.temp.4212842214.DROPPED.gZ
m = DROPPED_FILE_REGEX.match(os.path.basename(compressed_path))
if not m:
logging.error("could not extract file name from {}".format(compressed_path))
continue
target_path = os.path.join(target_dir, m.group(1))
result.append(target_path)
with gzip.open(compressed_path) as fp:
logging.debug("decompressing {}".format(compressed_path))
with open(target_path, 'wb') as dest_fp:
while True:
data = fp.read(io.DEFAULT_BUFFER_SIZE)
if data == b'':
break
dest_fp.write(data)
os.remove(compressed_path)
return result
finally:
try:
if temp_dir:
shutil.rmtree(temp_dir)
except Exception as e:
logging.error("unable to delete temporary directory {}: {}".format(temp_dir, e))
|
[
"def",
"download_dropped_files",
"(",
"self",
",",
"sha256",
",",
"environment_id",
",",
"target_dir",
")",
":",
"download_url",
"=",
"'{}/api/sample-dropped-files/{}?environmentId={}&apikey={}&secret={}'",
".",
"format",
"(",
"self",
".",
"url",
",",
"sha256",
",",
"environment_id",
",",
"self",
".",
"api_key",
",",
"self",
".",
"secret",
")",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"logging",
".",
"info",
"(",
"\"downloading dropped files from {}\"",
".",
"format",
"(",
"download_url",
")",
")",
"result",
"=",
"requests",
".",
"get",
"(",
"download_url",
",",
"verify",
"=",
"False",
",",
"headers",
"=",
"VXSTREAM_HEADERS",
",",
"proxies",
"=",
"self",
".",
"proxies",
")",
"# XXX",
"if",
"result",
".",
"status_code",
"!=",
"200",
":",
"logging",
".",
"error",
"(",
"\"got result {} from vxstream for {}: {}\"",
".",
"format",
"(",
"result",
".",
"status_code",
",",
"download_url",
",",
"result",
".",
"reason",
")",
")",
"return",
"None",
"# put what we download into a temporary directory",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"try",
":",
"# all dropped files come in a zip file",
"compressed_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"'download.zip'",
")",
"# write zip file to disk",
"with",
"open",
"(",
"compressed_path",
",",
"'wb'",
")",
"as",
"fp",
":",
"for",
"block",
"in",
"result",
".",
"iter_content",
"(",
"io",
".",
"DEFAULT_BUFFER_SIZE",
")",
":",
"fp",
".",
"write",
"(",
"block",
")",
"# unzip without paths",
"p",
"=",
"Popen",
"(",
"[",
"'7z'",
",",
"'e'",
",",
"'-y'",
",",
"'-o{}'",
".",
"format",
"(",
"target_dir",
")",
",",
"compressed_path",
"]",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
")",
"stdout",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",
")",
"try",
":",
"os",
".",
"remove",
"(",
"compressed_path",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"unable to delete {}: {}\"",
".",
"format",
"(",
"compressed_path",
",",
"e",
")",
")",
"# list gz files in drop_path",
"file_list",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"f",
")",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"target_dir",
")",
"if",
"f",
".",
"endswith",
"(",
"'.gz'",
")",
"]",
"result",
"=",
"[",
"]",
"for",
"compressed_path",
"in",
"file_list",
":",
"# there are some other files in here sometimes that we'll ignore",
"# we just want the dropped file",
"if",
"'.DROPPED.'",
"not",
"in",
"compressed_path",
":",
"continue",
"DROPPED_FILE_REGEX",
"=",
"re",
".",
"compile",
"(",
"r'^(.+?)\\.[0-9]+\\.DROPPED\\.gz'",
")",
"# the file paths look like this",
"# dropped/78QC7UOHAWCI47906LWH.temp.4212842214.DROPPED.gZ",
"m",
"=",
"DROPPED_FILE_REGEX",
".",
"match",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"compressed_path",
")",
")",
"if",
"not",
"m",
":",
"logging",
".",
"error",
"(",
"\"could not extract file name from {}\"",
".",
"format",
"(",
"compressed_path",
")",
")",
"continue",
"target_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"m",
".",
"group",
"(",
"1",
")",
")",
"result",
".",
"append",
"(",
"target_path",
")",
"with",
"gzip",
".",
"open",
"(",
"compressed_path",
")",
"as",
"fp",
":",
"logging",
".",
"debug",
"(",
"\"decompressing {}\"",
".",
"format",
"(",
"compressed_path",
")",
")",
"with",
"open",
"(",
"target_path",
",",
"'wb'",
")",
"as",
"dest_fp",
":",
"while",
"True",
":",
"data",
"=",
"fp",
".",
"read",
"(",
"io",
".",
"DEFAULT_BUFFER_SIZE",
")",
"if",
"data",
"==",
"b''",
":",
"break",
"dest_fp",
".",
"write",
"(",
"data",
")",
"os",
".",
"remove",
"(",
"compressed_path",
")",
"return",
"result",
"finally",
":",
"try",
":",
"if",
"temp_dir",
":",
"shutil",
".",
"rmtree",
"(",
"temp_dir",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"unable to delete temporary directory {}: {}\"",
".",
"format",
"(",
"temp_dir",
",",
"e",
")",
")"
] |
Downloads the dropped files for this sample into target_dir. Returns the list of files extracted.
|
[
"Downloads",
"the",
"dropped",
"files",
"for",
"this",
"sample",
"into",
"target_dir",
".",
"Returns",
"the",
"list",
"of",
"files",
"extracted",
"."
] |
cd82e3975215085cf929c5976f37083b9a3ac869
|
https://github.com/IntegralDefense/vxstreamlib/blob/cd82e3975215085cf929c5976f37083b9a3ac869/bin/vxstreamlib.py#L355-L436
|
245,411
|
IntegralDefense/vxstreamlib
|
bin/vxstreamlib.py
|
VxStreamServer.download_memory_dump
|
def download_memory_dump(self, sha256, environment_id, dest_dir):
"""Downloads the given memory dump into the given directory. Returns a tuple of a list of files extracted from what was downloaded, and the path to the combined memory dump."""
dest_path = os.path.join(dest_dir, 'memory.zip')
if self.download(sha256, environment_id, VXSTREAM_DOWNLOAD_MEMORY, dest_path) is None:
return None
with open(dest_path, 'rb') as fp:
blob = fp.read(1024)
if b'No dump files available' in blob:
logging.debug("memory dump not available for {} env {}".format(sha256, environment_id))
return None
logging.debug("extracting memory dump {} into {}".format(dest_path, dest_dir))
p = Popen(['7z', 'x', '-y', '-o{}'.format(dest_dir), dest_path], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
file_list = []
for file_path in [os.path.join(dest_dir, f) for f in os.listdir(dest_dir) if f != "memory.zip"]:
file_list.append(file_path)
# concatenate all these files into one file
dest_path = os.path.join(dest_dir, 'memory.combined.mdmp')
for file_path in file_list:
logging.debug("concatenating {}".format(file_path))
with open(file_path, 'rb') as input_fp:
with open(dest_path, 'ab') as output_fp:
while True:
data = input_fp.read(io.DEFAULT_BUFFER_SIZE)
if data == b'':
break
output_fp.write(data)
return file_list, dest_path
|
python
|
def download_memory_dump(self, sha256, environment_id, dest_dir):
"""Downloads the given memory dump into the given directory. Returns a tuple of a list of files extracted from what was downloaded, and the path to the combined memory dump."""
dest_path = os.path.join(dest_dir, 'memory.zip')
if self.download(sha256, environment_id, VXSTREAM_DOWNLOAD_MEMORY, dest_path) is None:
return None
with open(dest_path, 'rb') as fp:
blob = fp.read(1024)
if b'No dump files available' in blob:
logging.debug("memory dump not available for {} env {}".format(sha256, environment_id))
return None
logging.debug("extracting memory dump {} into {}".format(dest_path, dest_dir))
p = Popen(['7z', 'x', '-y', '-o{}'.format(dest_dir), dest_path], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
file_list = []
for file_path in [os.path.join(dest_dir, f) for f in os.listdir(dest_dir) if f != "memory.zip"]:
file_list.append(file_path)
# concatenate all these files into one file
dest_path = os.path.join(dest_dir, 'memory.combined.mdmp')
for file_path in file_list:
logging.debug("concatenating {}".format(file_path))
with open(file_path, 'rb') as input_fp:
with open(dest_path, 'ab') as output_fp:
while True:
data = input_fp.read(io.DEFAULT_BUFFER_SIZE)
if data == b'':
break
output_fp.write(data)
return file_list, dest_path
|
[
"def",
"download_memory_dump",
"(",
"self",
",",
"sha256",
",",
"environment_id",
",",
"dest_dir",
")",
":",
"dest_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest_dir",
",",
"'memory.zip'",
")",
"if",
"self",
".",
"download",
"(",
"sha256",
",",
"environment_id",
",",
"VXSTREAM_DOWNLOAD_MEMORY",
",",
"dest_path",
")",
"is",
"None",
":",
"return",
"None",
"with",
"open",
"(",
"dest_path",
",",
"'rb'",
")",
"as",
"fp",
":",
"blob",
"=",
"fp",
".",
"read",
"(",
"1024",
")",
"if",
"b'No dump files available'",
"in",
"blob",
":",
"logging",
".",
"debug",
"(",
"\"memory dump not available for {} env {}\"",
".",
"format",
"(",
"sha256",
",",
"environment_id",
")",
")",
"return",
"None",
"logging",
".",
"debug",
"(",
"\"extracting memory dump {} into {}\"",
".",
"format",
"(",
"dest_path",
",",
"dest_dir",
")",
")",
"p",
"=",
"Popen",
"(",
"[",
"'7z'",
",",
"'x'",
",",
"'-y'",
",",
"'-o{}'",
".",
"format",
"(",
"dest_dir",
")",
",",
"dest_path",
"]",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
")",
"stdout",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",
")",
"file_list",
"=",
"[",
"]",
"for",
"file_path",
"in",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dest_dir",
",",
"f",
")",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"dest_dir",
")",
"if",
"f",
"!=",
"\"memory.zip\"",
"]",
":",
"file_list",
".",
"append",
"(",
"file_path",
")",
"# concatenate all these files into one file",
"dest_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest_dir",
",",
"'memory.combined.mdmp'",
")",
"for",
"file_path",
"in",
"file_list",
":",
"logging",
".",
"debug",
"(",
"\"concatenating {}\"",
".",
"format",
"(",
"file_path",
")",
")",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"input_fp",
":",
"with",
"open",
"(",
"dest_path",
",",
"'ab'",
")",
"as",
"output_fp",
":",
"while",
"True",
":",
"data",
"=",
"input_fp",
".",
"read",
"(",
"io",
".",
"DEFAULT_BUFFER_SIZE",
")",
"if",
"data",
"==",
"b''",
":",
"break",
"output_fp",
".",
"write",
"(",
"data",
")",
"return",
"file_list",
",",
"dest_path"
] |
Downloads the given memory dump into the given directory. Returns a tuple of a list of files extracted from what was downloaded, and the path to the combined memory dump.
|
[
"Downloads",
"the",
"given",
"memory",
"dump",
"into",
"the",
"given",
"directory",
".",
"Returns",
"a",
"tuple",
"of",
"a",
"list",
"of",
"files",
"extracted",
"from",
"what",
"was",
"downloaded",
"and",
"the",
"path",
"to",
"the",
"combined",
"memory",
"dump",
"."
] |
cd82e3975215085cf929c5976f37083b9a3ac869
|
https://github.com/IntegralDefense/vxstreamlib/blob/cd82e3975215085cf929c5976f37083b9a3ac869/bin/vxstreamlib.py#L438-L472
|
245,412
|
emory-libraries/eulcommon
|
eulcommon/binfile/outlookexpress.py
|
MacMailMessage.data
|
def data(self):
'''email content for this message'''
# return data after any initial offset, plus content offset to
# skip header, up to the size of this message
return self.mmap[self.content_offset + self._offset: self._offset + self.size]
|
python
|
def data(self):
'''email content for this message'''
# return data after any initial offset, plus content offset to
# skip header, up to the size of this message
return self.mmap[self.content_offset + self._offset: self._offset + self.size]
|
[
"def",
"data",
"(",
"self",
")",
":",
"# return data after any initial offset, plus content offset to",
"# skip header, up to the size of this message",
"return",
"self",
".",
"mmap",
"[",
"self",
".",
"content_offset",
"+",
"self",
".",
"_offset",
":",
"self",
".",
"_offset",
"+",
"self",
".",
"size",
"]"
] |
email content for this message
|
[
"email",
"content",
"for",
"this",
"message"
] |
dc63a9b3b5e38205178235e0d716d1b28158d3a9
|
https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/binfile/outlookexpress.py#L166-L170
|
245,413
|
fakedrake/overlay_parse
|
overlay_parse/overlays.py
|
Overlay.copy
|
def copy(self, props=None, value=None):
"""
Copy the Overlay possibly overriding props.
"""
return Overlay(self.text,
(self.start, self.end),
props=props or self.props,
value=value or self.value)
|
python
|
def copy(self, props=None, value=None):
"""
Copy the Overlay possibly overriding props.
"""
return Overlay(self.text,
(self.start, self.end),
props=props or self.props,
value=value or self.value)
|
[
"def",
"copy",
"(",
"self",
",",
"props",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"return",
"Overlay",
"(",
"self",
".",
"text",
",",
"(",
"self",
".",
"start",
",",
"self",
".",
"end",
")",
",",
"props",
"=",
"props",
"or",
"self",
".",
"props",
",",
"value",
"=",
"value",
"or",
"self",
".",
"value",
")"
] |
Copy the Overlay possibly overriding props.
|
[
"Copy",
"the",
"Overlay",
"possibly",
"overriding",
"props",
"."
] |
9ac362d6aef1ea41aff7375af088c6ebef93d0cd
|
https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L41-L49
|
245,414
|
fakedrake/overlay_parse
|
overlay_parse/overlays.py
|
Overlay.match
|
def match(self, props=None, rng=None, offset=None):
"""
Provide any of the args and match or dont.
:param props: Should be a subset of my props.
:param rng: Exactly match my range.
:param offset: I start after this offset.
:returns: True if all the provided predicates match or are None
"""
if rng:
s, e = rng
else:
e = s = None
return ((e is None or self.end == e) and
(s is None or self.start == s)) and \
(props is None or props.issubset(self.props)) and \
(offset is None or self.start >= offset)
|
python
|
def match(self, props=None, rng=None, offset=None):
"""
Provide any of the args and match or dont.
:param props: Should be a subset of my props.
:param rng: Exactly match my range.
:param offset: I start after this offset.
:returns: True if all the provided predicates match or are None
"""
if rng:
s, e = rng
else:
e = s = None
return ((e is None or self.end == e) and
(s is None or self.start == s)) and \
(props is None or props.issubset(self.props)) and \
(offset is None or self.start >= offset)
|
[
"def",
"match",
"(",
"self",
",",
"props",
"=",
"None",
",",
"rng",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"if",
"rng",
":",
"s",
",",
"e",
"=",
"rng",
"else",
":",
"e",
"=",
"s",
"=",
"None",
"return",
"(",
"(",
"e",
"is",
"None",
"or",
"self",
".",
"end",
"==",
"e",
")",
"and",
"(",
"s",
"is",
"None",
"or",
"self",
".",
"start",
"==",
"s",
")",
")",
"and",
"(",
"props",
"is",
"None",
"or",
"props",
".",
"issubset",
"(",
"self",
".",
"props",
")",
")",
"and",
"(",
"offset",
"is",
"None",
"or",
"self",
".",
"start",
">=",
"offset",
")"
] |
Provide any of the args and match or dont.
:param props: Should be a subset of my props.
:param rng: Exactly match my range.
:param offset: I start after this offset.
:returns: True if all the provided predicates match or are None
|
[
"Provide",
"any",
"of",
"the",
"args",
"and",
"match",
"or",
"dont",
"."
] |
9ac362d6aef1ea41aff7375af088c6ebef93d0cd
|
https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L106-L124
|
245,415
|
fakedrake/overlay_parse
|
overlay_parse/overlays.py
|
OverlayedText.overlays_at
|
def overlays_at(self, key):
"""
Key may be a slice or a point.
"""
if isinstance(key, slice):
s, e, _ = key.indices(len(self.text))
else:
s = e = key
return [o for o in self.overlays if o.start in Rng(s, e)]
|
python
|
def overlays_at(self, key):
"""
Key may be a slice or a point.
"""
if isinstance(key, slice):
s, e, _ = key.indices(len(self.text))
else:
s = e = key
return [o for o in self.overlays if o.start in Rng(s, e)]
|
[
"def",
"overlays_at",
"(",
"self",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"slice",
")",
":",
"s",
",",
"e",
",",
"_",
"=",
"key",
".",
"indices",
"(",
"len",
"(",
"self",
".",
"text",
")",
")",
"else",
":",
"s",
"=",
"e",
"=",
"key",
"return",
"[",
"o",
"for",
"o",
"in",
"self",
".",
"overlays",
"if",
"o",
".",
"start",
"in",
"Rng",
"(",
"s",
",",
"e",
")",
"]"
] |
Key may be a slice or a point.
|
[
"Key",
"may",
"be",
"a",
"slice",
"or",
"a",
"point",
"."
] |
9ac362d6aef1ea41aff7375af088c6ebef93d0cd
|
https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L164-L174
|
245,416
|
fakedrake/overlay_parse
|
overlay_parse/overlays.py
|
OverlayedText.overlay
|
def overlay(self, matchers, force=False):
"""
Given a list of matchers create overlays based on them. Normally I
will remember what overlays were run this way and will avoid
re-running them but you can `force` me to. This is the
recommended way of running overlays.c
"""
for m in matchers:
if m in self._ran_matchers:
continue
self._ran_matchers.append(m)
self.overlays += list(m.offset_overlays(self))
self.overlays.sort(key=lambda o: o.start, reverse=True)
|
python
|
def overlay(self, matchers, force=False):
"""
Given a list of matchers create overlays based on them. Normally I
will remember what overlays were run this way and will avoid
re-running them but you can `force` me to. This is the
recommended way of running overlays.c
"""
for m in matchers:
if m in self._ran_matchers:
continue
self._ran_matchers.append(m)
self.overlays += list(m.offset_overlays(self))
self.overlays.sort(key=lambda o: o.start, reverse=True)
|
[
"def",
"overlay",
"(",
"self",
",",
"matchers",
",",
"force",
"=",
"False",
")",
":",
"for",
"m",
"in",
"matchers",
":",
"if",
"m",
"in",
"self",
".",
"_ran_matchers",
":",
"continue",
"self",
".",
"_ran_matchers",
".",
"append",
"(",
"m",
")",
"self",
".",
"overlays",
"+=",
"list",
"(",
"m",
".",
"offset_overlays",
"(",
"self",
")",
")",
"self",
".",
"overlays",
".",
"sort",
"(",
"key",
"=",
"lambda",
"o",
":",
"o",
".",
"start",
",",
"reverse",
"=",
"True",
")"
] |
Given a list of matchers create overlays based on them. Normally I
will remember what overlays were run this way and will avoid
re-running them but you can `force` me to. This is the
recommended way of running overlays.c
|
[
"Given",
"a",
"list",
"of",
"matchers",
"create",
"overlays",
"based",
"on",
"them",
".",
"Normally",
"I",
"will",
"remember",
"what",
"overlays",
"were",
"run",
"this",
"way",
"and",
"will",
"avoid",
"re",
"-",
"running",
"them",
"but",
"you",
"can",
"force",
"me",
"to",
".",
"This",
"is",
"the",
"recommended",
"way",
"of",
"running",
"overlays",
".",
"c"
] |
9ac362d6aef1ea41aff7375af088c6ebef93d0cd
|
https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L176-L191
|
245,417
|
icio/evil
|
evil/__init__.py
|
evil
|
def evil(expr, lookup, operators, cast, reducer, tokenizer):
"""evil evaluates an expression according to the eval description given.
:param expr: An expression to evaluate.
:param lookup: A callable which takes a single pattern argument and returns
a set of results. The pattern can be anything that is not an
operator token or round brackets.
:param operators: A precedence-ordered dictionary of (function, side)
tuples keyed on the operator token.
:param reducer: A callable which takes a sequential list of values (from
operations or lookups) and combines them into a result.
Typical behaviour is that of the + operator. The return
type should be the same as cast.
:param cast: A callable which transforms the results of the lookup into
the type expected by the operators and the type of the result.
:param tokenizer: A callable which will break the query into tokens for
evaluation per the lookup and operators. Defaults to
setquery.query_tokenizer.
:raises: SyntaxError
:returns:
"""
operators = OrderedDict((op[0], op[1:]) for op in operators)
if "(" in operators or ")" in operators:
raise ValueError("( and ) are reserved operators")
operator_tokens = ["(", ")"] + operators.keys()
tokens = iter(tokenizer(expr, operator_tokens))
levels = [[]]
while True:
# Token evaluation and pattern lookups
expr = levels.pop() # The currently-constructed expression
new_level = False # We should step into a subexpression
first_token = len(expr) == 0 # The first (sub)exp. token
prev_op_side = None # The side of the last-seen operator
try:
# Try to get the side of the last operator from an expression
# which we are going to continue constructing.
prev_op_side = operators[expr[-1]][1]
except:
pass
for token in tokens:
if token == "(":
new_level = True
break
elif token == ")":
break
elif token in operators:
op_side = operators[token][1]
if first_token and op_side & OP_LEFT:
raise SyntaxError("Operators which act on expressions to "
"their left or both sides cannot be at "
"the beginning of an expression.")
if prev_op_side is not None:
if prev_op_side & OP_RIGHT and op_side & OP_LEFT:
raise SyntaxError("Operators cannot be beside one "
"another if they act on expressions "
"facing one-another.")
expr.append(token)
prev_op_side = op_side
continue
else:
expr.append(cast(lookup(token)))
prev_op_side = None
first_token = False
if new_level:
levels.append(expr)
levels.append([])
continue
elif prev_op_side is not None and prev_op_side & OP_RIGHT:
raise SyntaxError("Operators which act on expressions to their "
"right or both sides cannot be at the end of "
"an expression.")
# Operator evaluation
explen = len(expr)
for op, (op_eval, op_side) in operators.iteritems():
if op_side is OP_RIGHT:
# Apply right-sided operators. We loop from the end backward so
# that multiple such operators next to noe another are resolved
# in the correct order
t = explen - 1
while t >= 0:
if expr[t] == op:
expr[t] = op_eval(expr[t + 1])
del expr[t + 1]
explen -= 1
t -= 1
else:
# Apply left- and both-sided operators. We loop forward so that
# that multiple such operators next to one another are resolved
# in the correct order.
t = 0
while t < explen:
if expr[t] == op:
# Apply left- or both-sided operators
if op_side is OP_LEFT:
expr[t] = op_eval(expr[t - 1])
del expr[t - 1]
t -= 1
explen -= 1
elif op_side is OP_BOTH:
expr[t] = op_eval(expr[t - 1], expr[t + 1])
del expr[t + 1], expr[t - 1]
t -= 1
explen -= 2
t += 1
if len(levels) > 0:
levels[-1].append(reducer(expr))
else:
break
return reducer(expr)
|
python
|
def evil(expr, lookup, operators, cast, reducer, tokenizer):
"""evil evaluates an expression according to the eval description given.
:param expr: An expression to evaluate.
:param lookup: A callable which takes a single pattern argument and returns
a set of results. The pattern can be anything that is not an
operator token or round brackets.
:param operators: A precedence-ordered dictionary of (function, side)
tuples keyed on the operator token.
:param reducer: A callable which takes a sequential list of values (from
operations or lookups) and combines them into a result.
Typical behaviour is that of the + operator. The return
type should be the same as cast.
:param cast: A callable which transforms the results of the lookup into
the type expected by the operators and the type of the result.
:param tokenizer: A callable which will break the query into tokens for
evaluation per the lookup and operators. Defaults to
setquery.query_tokenizer.
:raises: SyntaxError
:returns:
"""
operators = OrderedDict((op[0], op[1:]) for op in operators)
if "(" in operators or ")" in operators:
raise ValueError("( and ) are reserved operators")
operator_tokens = ["(", ")"] + operators.keys()
tokens = iter(tokenizer(expr, operator_tokens))
levels = [[]]
while True:
# Token evaluation and pattern lookups
expr = levels.pop() # The currently-constructed expression
new_level = False # We should step into a subexpression
first_token = len(expr) == 0 # The first (sub)exp. token
prev_op_side = None # The side of the last-seen operator
try:
# Try to get the side of the last operator from an expression
# which we are going to continue constructing.
prev_op_side = operators[expr[-1]][1]
except:
pass
for token in tokens:
if token == "(":
new_level = True
break
elif token == ")":
break
elif token in operators:
op_side = operators[token][1]
if first_token and op_side & OP_LEFT:
raise SyntaxError("Operators which act on expressions to "
"their left or both sides cannot be at "
"the beginning of an expression.")
if prev_op_side is not None:
if prev_op_side & OP_RIGHT and op_side & OP_LEFT:
raise SyntaxError("Operators cannot be beside one "
"another if they act on expressions "
"facing one-another.")
expr.append(token)
prev_op_side = op_side
continue
else:
expr.append(cast(lookup(token)))
prev_op_side = None
first_token = False
if new_level:
levels.append(expr)
levels.append([])
continue
elif prev_op_side is not None and prev_op_side & OP_RIGHT:
raise SyntaxError("Operators which act on expressions to their "
"right or both sides cannot be at the end of "
"an expression.")
# Operator evaluation
explen = len(expr)
for op, (op_eval, op_side) in operators.iteritems():
if op_side is OP_RIGHT:
# Apply right-sided operators. We loop from the end backward so
# that multiple such operators next to noe another are resolved
# in the correct order
t = explen - 1
while t >= 0:
if expr[t] == op:
expr[t] = op_eval(expr[t + 1])
del expr[t + 1]
explen -= 1
t -= 1
else:
# Apply left- and both-sided operators. We loop forward so that
# that multiple such operators next to one another are resolved
# in the correct order.
t = 0
while t < explen:
if expr[t] == op:
# Apply left- or both-sided operators
if op_side is OP_LEFT:
expr[t] = op_eval(expr[t - 1])
del expr[t - 1]
t -= 1
explen -= 1
elif op_side is OP_BOTH:
expr[t] = op_eval(expr[t - 1], expr[t + 1])
del expr[t + 1], expr[t - 1]
t -= 1
explen -= 2
t += 1
if len(levels) > 0:
levels[-1].append(reducer(expr))
else:
break
return reducer(expr)
|
[
"def",
"evil",
"(",
"expr",
",",
"lookup",
",",
"operators",
",",
"cast",
",",
"reducer",
",",
"tokenizer",
")",
":",
"operators",
"=",
"OrderedDict",
"(",
"(",
"op",
"[",
"0",
"]",
",",
"op",
"[",
"1",
":",
"]",
")",
"for",
"op",
"in",
"operators",
")",
"if",
"\"(\"",
"in",
"operators",
"or",
"\")\"",
"in",
"operators",
":",
"raise",
"ValueError",
"(",
"\"( and ) are reserved operators\"",
")",
"operator_tokens",
"=",
"[",
"\"(\"",
",",
"\")\"",
"]",
"+",
"operators",
".",
"keys",
"(",
")",
"tokens",
"=",
"iter",
"(",
"tokenizer",
"(",
"expr",
",",
"operator_tokens",
")",
")",
"levels",
"=",
"[",
"[",
"]",
"]",
"while",
"True",
":",
"# Token evaluation and pattern lookups",
"expr",
"=",
"levels",
".",
"pop",
"(",
")",
"# The currently-constructed expression",
"new_level",
"=",
"False",
"# We should step into a subexpression",
"first_token",
"=",
"len",
"(",
"expr",
")",
"==",
"0",
"# The first (sub)exp. token",
"prev_op_side",
"=",
"None",
"# The side of the last-seen operator",
"try",
":",
"# Try to get the side of the last operator from an expression",
"# which we are going to continue constructing.",
"prev_op_side",
"=",
"operators",
"[",
"expr",
"[",
"-",
"1",
"]",
"]",
"[",
"1",
"]",
"except",
":",
"pass",
"for",
"token",
"in",
"tokens",
":",
"if",
"token",
"==",
"\"(\"",
":",
"new_level",
"=",
"True",
"break",
"elif",
"token",
"==",
"\")\"",
":",
"break",
"elif",
"token",
"in",
"operators",
":",
"op_side",
"=",
"operators",
"[",
"token",
"]",
"[",
"1",
"]",
"if",
"first_token",
"and",
"op_side",
"&",
"OP_LEFT",
":",
"raise",
"SyntaxError",
"(",
"\"Operators which act on expressions to \"",
"\"their left or both sides cannot be at \"",
"\"the beginning of an expression.\"",
")",
"if",
"prev_op_side",
"is",
"not",
"None",
":",
"if",
"prev_op_side",
"&",
"OP_RIGHT",
"and",
"op_side",
"&",
"OP_LEFT",
":",
"raise",
"SyntaxError",
"(",
"\"Operators cannot be beside one \"",
"\"another if they act on expressions \"",
"\"facing one-another.\"",
")",
"expr",
".",
"append",
"(",
"token",
")",
"prev_op_side",
"=",
"op_side",
"continue",
"else",
":",
"expr",
".",
"append",
"(",
"cast",
"(",
"lookup",
"(",
"token",
")",
")",
")",
"prev_op_side",
"=",
"None",
"first_token",
"=",
"False",
"if",
"new_level",
":",
"levels",
".",
"append",
"(",
"expr",
")",
"levels",
".",
"append",
"(",
"[",
"]",
")",
"continue",
"elif",
"prev_op_side",
"is",
"not",
"None",
"and",
"prev_op_side",
"&",
"OP_RIGHT",
":",
"raise",
"SyntaxError",
"(",
"\"Operators which act on expressions to their \"",
"\"right or both sides cannot be at the end of \"",
"\"an expression.\"",
")",
"# Operator evaluation",
"explen",
"=",
"len",
"(",
"expr",
")",
"for",
"op",
",",
"(",
"op_eval",
",",
"op_side",
")",
"in",
"operators",
".",
"iteritems",
"(",
")",
":",
"if",
"op_side",
"is",
"OP_RIGHT",
":",
"# Apply right-sided operators. We loop from the end backward so",
"# that multiple such operators next to noe another are resolved",
"# in the correct order",
"t",
"=",
"explen",
"-",
"1",
"while",
"t",
">=",
"0",
":",
"if",
"expr",
"[",
"t",
"]",
"==",
"op",
":",
"expr",
"[",
"t",
"]",
"=",
"op_eval",
"(",
"expr",
"[",
"t",
"+",
"1",
"]",
")",
"del",
"expr",
"[",
"t",
"+",
"1",
"]",
"explen",
"-=",
"1",
"t",
"-=",
"1",
"else",
":",
"# Apply left- and both-sided operators. We loop forward so that",
"# that multiple such operators next to one another are resolved",
"# in the correct order.",
"t",
"=",
"0",
"while",
"t",
"<",
"explen",
":",
"if",
"expr",
"[",
"t",
"]",
"==",
"op",
":",
"# Apply left- or both-sided operators",
"if",
"op_side",
"is",
"OP_LEFT",
":",
"expr",
"[",
"t",
"]",
"=",
"op_eval",
"(",
"expr",
"[",
"t",
"-",
"1",
"]",
")",
"del",
"expr",
"[",
"t",
"-",
"1",
"]",
"t",
"-=",
"1",
"explen",
"-=",
"1",
"elif",
"op_side",
"is",
"OP_BOTH",
":",
"expr",
"[",
"t",
"]",
"=",
"op_eval",
"(",
"expr",
"[",
"t",
"-",
"1",
"]",
",",
"expr",
"[",
"t",
"+",
"1",
"]",
")",
"del",
"expr",
"[",
"t",
"+",
"1",
"]",
",",
"expr",
"[",
"t",
"-",
"1",
"]",
"t",
"-=",
"1",
"explen",
"-=",
"2",
"t",
"+=",
"1",
"if",
"len",
"(",
"levels",
")",
">",
"0",
":",
"levels",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"reducer",
"(",
"expr",
")",
")",
"else",
":",
"break",
"return",
"reducer",
"(",
"expr",
")"
] |
evil evaluates an expression according to the eval description given.
:param expr: An expression to evaluate.
:param lookup: A callable which takes a single pattern argument and returns
a set of results. The pattern can be anything that is not an
operator token or round brackets.
:param operators: A precedence-ordered dictionary of (function, side)
tuples keyed on the operator token.
:param reducer: A callable which takes a sequential list of values (from
operations or lookups) and combines them into a result.
Typical behaviour is that of the + operator. The return
type should be the same as cast.
:param cast: A callable which transforms the results of the lookup into
the type expected by the operators and the type of the result.
:param tokenizer: A callable which will break the query into tokens for
evaluation per the lookup and operators. Defaults to
setquery.query_tokenizer.
:raises: SyntaxError
:returns:
|
[
"evil",
"evaluates",
"an",
"expression",
"according",
"to",
"the",
"eval",
"description",
"given",
"."
] |
6f12d16652951fb60ac238cef203eaa585ec0a28
|
https://github.com/icio/evil/blob/6f12d16652951fb60ac238cef203eaa585ec0a28/evil/__init__.py#L13-L137
|
245,418
|
icio/evil
|
evil/__init__.py
|
op
|
def op(token, func, left=False, right=False):
"""op provides a more verbose syntax for declaring operators.
:param token: The string token of the operator. Usually a single character.
:param func: A callable used to evaluate its arguments. Where the operator
is both-sided the callable should accept two arguments. Where
it is one-sided it should accept one argument.
:param left: A boolean indicating whether the operator applies to the
expression to the left of it.
:param right: A boolean indicating whether the operator applies to the
expression to the right of it.
:returns: a tuple (token, func, side) where side is OP_BOTH if left and
right (or neither) and OP_LEFT if left, otherwise OP_RIGHT.
"""
both = (left == right)
return (token, func, OP_BOTH if both else OP_LEFT if left else OP_RIGHT)
|
python
|
def op(token, func, left=False, right=False):
"""op provides a more verbose syntax for declaring operators.
:param token: The string token of the operator. Usually a single character.
:param func: A callable used to evaluate its arguments. Where the operator
is both-sided the callable should accept two arguments. Where
it is one-sided it should accept one argument.
:param left: A boolean indicating whether the operator applies to the
expression to the left of it.
:param right: A boolean indicating whether the operator applies to the
expression to the right of it.
:returns: a tuple (token, func, side) where side is OP_BOTH if left and
right (or neither) and OP_LEFT if left, otherwise OP_RIGHT.
"""
both = (left == right)
return (token, func, OP_BOTH if both else OP_LEFT if left else OP_RIGHT)
|
[
"def",
"op",
"(",
"token",
",",
"func",
",",
"left",
"=",
"False",
",",
"right",
"=",
"False",
")",
":",
"both",
"=",
"(",
"left",
"==",
"right",
")",
"return",
"(",
"token",
",",
"func",
",",
"OP_BOTH",
"if",
"both",
"else",
"OP_LEFT",
"if",
"left",
"else",
"OP_RIGHT",
")"
] |
op provides a more verbose syntax for declaring operators.
:param token: The string token of the operator. Usually a single character.
:param func: A callable used to evaluate its arguments. Where the operator
is both-sided the callable should accept two arguments. Where
it is one-sided it should accept one argument.
:param left: A boolean indicating whether the operator applies to the
expression to the left of it.
:param right: A boolean indicating whether the operator applies to the
expression to the right of it.
:returns: a tuple (token, func, side) where side is OP_BOTH if left and
right (or neither) and OP_LEFT if left, otherwise OP_RIGHT.
|
[
"op",
"provides",
"a",
"more",
"verbose",
"syntax",
"for",
"declaring",
"operators",
"."
] |
6f12d16652951fb60ac238cef203eaa585ec0a28
|
https://github.com/icio/evil/blob/6f12d16652951fb60ac238cef203eaa585ec0a28/evil/__init__.py#L164-L180
|
245,419
|
icio/evil
|
evil/__init__.py
|
globlookup
|
def globlookup(pattern, root):
"""globlookup finds filesystem objects whose relative path matches the
given pattern.
:param pattern: The pattern to wish to match relative filepaths to.
:param root: The root director to search within.
"""
for subdir, dirnames, filenames in os.walk(root):
d = subdir[len(root) + 1:]
files = (os.path.join(d, f) for f in filenames)
for f in fnmatch.filter(files, pattern):
yield f
|
python
|
def globlookup(pattern, root):
"""globlookup finds filesystem objects whose relative path matches the
given pattern.
:param pattern: The pattern to wish to match relative filepaths to.
:param root: The root director to search within.
"""
for subdir, dirnames, filenames in os.walk(root):
d = subdir[len(root) + 1:]
files = (os.path.join(d, f) for f in filenames)
for f in fnmatch.filter(files, pattern):
yield f
|
[
"def",
"globlookup",
"(",
"pattern",
",",
"root",
")",
":",
"for",
"subdir",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"root",
")",
":",
"d",
"=",
"subdir",
"[",
"len",
"(",
"root",
")",
"+",
"1",
":",
"]",
"files",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"f",
")",
"for",
"f",
"in",
"filenames",
")",
"for",
"f",
"in",
"fnmatch",
".",
"filter",
"(",
"files",
",",
"pattern",
")",
":",
"yield",
"f"
] |
globlookup finds filesystem objects whose relative path matches the
given pattern.
:param pattern: The pattern to wish to match relative filepaths to.
:param root: The root director to search within.
|
[
"globlookup",
"finds",
"filesystem",
"objects",
"whose",
"relative",
"path",
"matches",
"the",
"given",
"pattern",
"."
] |
6f12d16652951fb60ac238cef203eaa585ec0a28
|
https://github.com/icio/evil/blob/6f12d16652951fb60ac238cef203eaa585ec0a28/evil/__init__.py#L193-L205
|
245,420
|
sassoo/goldman
|
goldman/resources/related.py
|
Resource.on_get
|
def on_get(self, req, resp, rid, related):
""" Find the related model & serialize it back
If the parent resource of the related model doesn't
exist then abort on a 404.
"""
signals.pre_req.send(self.model)
signals.pre_req_find.send(self.model)
if not hasattr(self.model, related):
abort(InvalidURL(**{
'detail': 'The "%s" resource does not have a related '
'resource named "%s". This is an error, check '
'your spelling & retry.' % (self.rtype, related)
}))
model = find(self.model, rid)
try:
model_related = getattr(model, related).load()
except AttributeError:
model_related = None
if isinstance(model_related, list):
props = to_rest_models(model_related, includes=req.includes)
elif model:
props = to_rest_model(model_related, includes=req.includes)
else:
props = model_related
resp.serialize(props)
signals.post_req.send(self.model)
signals.post_req_find.send(self.model)
|
python
|
def on_get(self, req, resp, rid, related):
""" Find the related model & serialize it back
If the parent resource of the related model doesn't
exist then abort on a 404.
"""
signals.pre_req.send(self.model)
signals.pre_req_find.send(self.model)
if not hasattr(self.model, related):
abort(InvalidURL(**{
'detail': 'The "%s" resource does not have a related '
'resource named "%s". This is an error, check '
'your spelling & retry.' % (self.rtype, related)
}))
model = find(self.model, rid)
try:
model_related = getattr(model, related).load()
except AttributeError:
model_related = None
if isinstance(model_related, list):
props = to_rest_models(model_related, includes=req.includes)
elif model:
props = to_rest_model(model_related, includes=req.includes)
else:
props = model_related
resp.serialize(props)
signals.post_req.send(self.model)
signals.post_req_find.send(self.model)
|
[
"def",
"on_get",
"(",
"self",
",",
"req",
",",
"resp",
",",
"rid",
",",
"related",
")",
":",
"signals",
".",
"pre_req",
".",
"send",
"(",
"self",
".",
"model",
")",
"signals",
".",
"pre_req_find",
".",
"send",
"(",
"self",
".",
"model",
")",
"if",
"not",
"hasattr",
"(",
"self",
".",
"model",
",",
"related",
")",
":",
"abort",
"(",
"InvalidURL",
"(",
"*",
"*",
"{",
"'detail'",
":",
"'The \"%s\" resource does not have a related '",
"'resource named \"%s\". This is an error, check '",
"'your spelling & retry.'",
"%",
"(",
"self",
".",
"rtype",
",",
"related",
")",
"}",
")",
")",
"model",
"=",
"find",
"(",
"self",
".",
"model",
",",
"rid",
")",
"try",
":",
"model_related",
"=",
"getattr",
"(",
"model",
",",
"related",
")",
".",
"load",
"(",
")",
"except",
"AttributeError",
":",
"model_related",
"=",
"None",
"if",
"isinstance",
"(",
"model_related",
",",
"list",
")",
":",
"props",
"=",
"to_rest_models",
"(",
"model_related",
",",
"includes",
"=",
"req",
".",
"includes",
")",
"elif",
"model",
":",
"props",
"=",
"to_rest_model",
"(",
"model_related",
",",
"includes",
"=",
"req",
".",
"includes",
")",
"else",
":",
"props",
"=",
"model_related",
"resp",
".",
"serialize",
"(",
"props",
")",
"signals",
".",
"post_req",
".",
"send",
"(",
"self",
".",
"model",
")",
"signals",
".",
"post_req_find",
".",
"send",
"(",
"self",
".",
"model",
")"
] |
Find the related model & serialize it back
If the parent resource of the related model doesn't
exist then abort on a 404.
|
[
"Find",
"the",
"related",
"model",
"&",
"serialize",
"it",
"back"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/resources/related.py#L43-L76
|
245,421
|
PyMLGame/pymlgame
|
emulator.py
|
Emu.recv_data
|
def recv_data(self):
"""
Grab the next frame and put it on the matrix.
"""
data, addr = self.sock.recvfrom(self.packetsize)
matrix = map(ord, data.strip())
if len(matrix) == self.packetsize:
self.matrix = matrix[:-4]
|
python
|
def recv_data(self):
"""
Grab the next frame and put it on the matrix.
"""
data, addr = self.sock.recvfrom(self.packetsize)
matrix = map(ord, data.strip())
if len(matrix) == self.packetsize:
self.matrix = matrix[:-4]
|
[
"def",
"recv_data",
"(",
"self",
")",
":",
"data",
",",
"addr",
"=",
"self",
".",
"sock",
".",
"recvfrom",
"(",
"self",
".",
"packetsize",
")",
"matrix",
"=",
"map",
"(",
"ord",
",",
"data",
".",
"strip",
"(",
")",
")",
"if",
"len",
"(",
"matrix",
")",
"==",
"self",
".",
"packetsize",
":",
"self",
".",
"matrix",
"=",
"matrix",
"[",
":",
"-",
"4",
"]"
] |
Grab the next frame and put it on the matrix.
|
[
"Grab",
"the",
"next",
"frame",
"and",
"put",
"it",
"on",
"the",
"matrix",
"."
] |
450fe77d35f9a26c107586d6954f69c3895bf504
|
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/emulator.py#L67-L74
|
245,422
|
PyMLGame/pymlgame
|
emulator.py
|
Emu.update
|
def update(self):
"""
Generate the output from the matrix.
"""
pixels = len(self.matrix)
for x in range(self.width):
for y in range(self.height):
pixel = y * self.width * 3 + x * 3
#TODO: sometimes the matrix is not as big as it should
if pixel < pixels:
pygame.draw.circle(self.screen,
(self.matrix[pixel], self.matrix[pixel + 1], self.matrix[pixel + 2]),
(x * self.dotsize + self.dotsize / 2, y * self.dotsize + self.dotsize / 2), self.dotsize / 2, 0)
|
python
|
def update(self):
"""
Generate the output from the matrix.
"""
pixels = len(self.matrix)
for x in range(self.width):
for y in range(self.height):
pixel = y * self.width * 3 + x * 3
#TODO: sometimes the matrix is not as big as it should
if pixel < pixels:
pygame.draw.circle(self.screen,
(self.matrix[pixel], self.matrix[pixel + 1], self.matrix[pixel + 2]),
(x * self.dotsize + self.dotsize / 2, y * self.dotsize + self.dotsize / 2), self.dotsize / 2, 0)
|
[
"def",
"update",
"(",
"self",
")",
":",
"pixels",
"=",
"len",
"(",
"self",
".",
"matrix",
")",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"width",
")",
":",
"for",
"y",
"in",
"range",
"(",
"self",
".",
"height",
")",
":",
"pixel",
"=",
"y",
"*",
"self",
".",
"width",
"*",
"3",
"+",
"x",
"*",
"3",
"#TODO: sometimes the matrix is not as big as it should",
"if",
"pixel",
"<",
"pixels",
":",
"pygame",
".",
"draw",
".",
"circle",
"(",
"self",
".",
"screen",
",",
"(",
"self",
".",
"matrix",
"[",
"pixel",
"]",
",",
"self",
".",
"matrix",
"[",
"pixel",
"+",
"1",
"]",
",",
"self",
".",
"matrix",
"[",
"pixel",
"+",
"2",
"]",
")",
",",
"(",
"x",
"*",
"self",
".",
"dotsize",
"+",
"self",
".",
"dotsize",
"/",
"2",
",",
"y",
"*",
"self",
".",
"dotsize",
"+",
"self",
".",
"dotsize",
"/",
"2",
")",
",",
"self",
".",
"dotsize",
"/",
"2",
",",
"0",
")"
] |
Generate the output from the matrix.
|
[
"Generate",
"the",
"output",
"from",
"the",
"matrix",
"."
] |
450fe77d35f9a26c107586d6954f69c3895bf504
|
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/emulator.py#L76-L88
|
245,423
|
PyMLGame/pymlgame
|
emulator.py
|
Emu.gameloop
|
def gameloop(self):
"""
Loop through all the necessary stuff and end execution when Ctrl+C was hit.
"""
try:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
self.recv_data()
self.update()
self.render()
except KeyboardInterrupt:
pass
|
python
|
def gameloop(self):
"""
Loop through all the necessary stuff and end execution when Ctrl+C was hit.
"""
try:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
self.recv_data()
self.update()
self.render()
except KeyboardInterrupt:
pass
|
[
"def",
"gameloop",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"for",
"event",
"in",
"pygame",
".",
"event",
".",
"get",
"(",
")",
":",
"if",
"event",
".",
"type",
"==",
"pygame",
".",
"QUIT",
":",
"sys",
".",
"exit",
"(",
")",
"if",
"event",
".",
"type",
"==",
"pygame",
".",
"KEYDOWN",
":",
"if",
"event",
".",
"key",
"==",
"pygame",
".",
"K_ESCAPE",
":",
"pygame",
".",
"event",
".",
"post",
"(",
"pygame",
".",
"event",
".",
"Event",
"(",
"pygame",
".",
"QUIT",
")",
")",
"self",
".",
"recv_data",
"(",
")",
"self",
".",
"update",
"(",
")",
"self",
".",
"render",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"pass"
] |
Loop through all the necessary stuff and end execution when Ctrl+C was hit.
|
[
"Loop",
"through",
"all",
"the",
"necessary",
"stuff",
"and",
"end",
"execution",
"when",
"Ctrl",
"+",
"C",
"was",
"hit",
"."
] |
450fe77d35f9a26c107586d6954f69c3895bf504
|
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/emulator.py#L97-L114
|
245,424
|
maxfischer2781/chainlet
|
chainlet/wrapper.py
|
getname
|
def getname(obj):
"""
Return the most qualified name of an object
:param obj: object to fetch name
:return: name of ``obj``
"""
for name_attribute in ('__qualname__', '__name__'):
try:
# an object always has a class, as per Python data model
return getattr(obj, name_attribute, getattr(obj.__class__, name_attribute))
except AttributeError:
pass
raise TypeError('object of type %r does not define a canonical name' % type(obj))
|
python
|
def getname(obj):
"""
Return the most qualified name of an object
:param obj: object to fetch name
:return: name of ``obj``
"""
for name_attribute in ('__qualname__', '__name__'):
try:
# an object always has a class, as per Python data model
return getattr(obj, name_attribute, getattr(obj.__class__, name_attribute))
except AttributeError:
pass
raise TypeError('object of type %r does not define a canonical name' % type(obj))
|
[
"def",
"getname",
"(",
"obj",
")",
":",
"for",
"name_attribute",
"in",
"(",
"'__qualname__'",
",",
"'__name__'",
")",
":",
"try",
":",
"# an object always has a class, as per Python data model",
"return",
"getattr",
"(",
"obj",
",",
"name_attribute",
",",
"getattr",
"(",
"obj",
".",
"__class__",
",",
"name_attribute",
")",
")",
"except",
"AttributeError",
":",
"pass",
"raise",
"TypeError",
"(",
"'object of type %r does not define a canonical name'",
"%",
"type",
"(",
"obj",
")",
")"
] |
Return the most qualified name of an object
:param obj: object to fetch name
:return: name of ``obj``
|
[
"Return",
"the",
"most",
"qualified",
"name",
"of",
"an",
"object"
] |
4e17f9992b4780bd0d9309202e2847df640bffe8
|
https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/wrapper.py#L5-L18
|
245,425
|
maxfischer2781/chainlet
|
chainlet/wrapper.py
|
WrapperMixin.wraplet
|
def wraplet(cls, *cls_args, **cls_kwargs):
"""
Create a factory to produce a Wrapper from a slave factory
:param cls_args: positional arguments to provide to the Wrapper class
:param cls_kwargs: keyword arguments to provide to the Wrapper class
:return:
.. code:: python
cls_wrapper_factory = cls.wraplet(*cls_args, **cls_kwargs)
link_factory = cls_wrapper_factory(slave_factory)
slave_link = link_factory(*slave_args, **slave_kwargs)
"""
if cls.__init_slave__ in (None, WrapperMixin.__init_slave__):
raise TypeError('type %r does not implement the wraplet protocol' % getname(cls))
def wrapper_factory(slave_factory):
"""Factory to create a new class by wrapping ``slave_factory``"""
class Wraplet(cls): # pylint:disable=abstract-method
_slave_factory = staticmethod(slave_factory)
# Assign the wrapped attributes directly instead of
# using functools.wraps, as we may deal with arbitrarry
# class/callable combinations.
__doc__ = slave_factory.__doc__
# While the wrapped instance wraps the slave, the
# wrapper class wraps the slave factory. Any instance
# then just hides the class level attribute.
# Exposing __wrapped__ here allows introspection,such
# as inspect.signature, to pick up metadata.
__wrapped__ = slave_factory
# In Py3.X, objects without any annotations just provide an
# empty dict.
__annotations__ = getattr(slave_factory, '__annotations__', {})
def __init__(self, *slave_args, **slave_kwargs):
slave = self.__init_slave__(self._slave_factory, *slave_args, **slave_kwargs)
super(Wraplet, self).__init__(slave, *cls_args, **cls_kwargs)
__repr__ = cls.__wraplet_repr__
# swap places with our target so that both can be pickled/unpickled
Wraplet.__name__ = getname(slave_factory).split('.')[-1]
Wraplet.__qualname__ = getname(slave_factory)
Wraplet.__module__ = slave_factory.__module__
# this is enough for Py3.4+ to find the slave
slave_factory.__qualname__ = Wraplet.__qualname__ + '._slave_factory'
# ## This is an EVIL hack! Do not use use this at home unless you understand it! ##
# enable python2 lookup of the slave via its wrapper
# This allows to implicitly pickle slave objects which already support pickle,
# e.g. function and partial.
# python2 pickle performs the equivalent of getattr(sys.modules[obj.__module__, obj.__name__]
# which does not allow dotted name lookups. To work around this, we place the slave into the
# module, globally, using the qualified name *explicitly*. As qualified names are not valid identifiers,
# this will not create a collision unless someone tries to do the same trick.
if sys.version_info[:2] <= (3, 4):
# While 3.4 adds support for using __qualname__, that is *only* for protocol 4. Older
# protocols still require __name__. However, 3.4 *explicitly* disallows using dotted names,
# which defeats the obvious way of injecting the proper dotted name. Instead, an illegal name
# using : in place of . is used, which should also not conflict.
name_separator = '.' if sys.version_info[:2] != (3, 4) else ':'
# Make sure we actually register the correct entity
# Since we are only working with __name__, the slave could be defined
# in an inner scope. In this case, registering it in the global namespace
# may increase its lifetime, or replace an actual global slave of the
# same name.
# There are two cases we have to check here:
# slave = wraplet(slave)
# The slave already exists in the module namespace, with its __name__.
# The object with that name must be *identical* to the slave.
# @wraplet\ndef slave
# Neither slave nor Wrapper exist in the namespace yet (they are only bound *after*
# the wraplet returns). No object may exist with the same name.
if getattr(sys.modules[slave_factory.__module__], slave_factory.__name__, slave_factory) is slave_factory:
slave_factory.__name__ += name_separator + '_slave_factory'
setattr(sys.modules[slave_factory.__module__], slave_factory.__name__, slave_factory)
return Wraplet
return wrapper_factory
|
python
|
def wraplet(cls, *cls_args, **cls_kwargs):
"""
Create a factory to produce a Wrapper from a slave factory
:param cls_args: positional arguments to provide to the Wrapper class
:param cls_kwargs: keyword arguments to provide to the Wrapper class
:return:
.. code:: python
cls_wrapper_factory = cls.wraplet(*cls_args, **cls_kwargs)
link_factory = cls_wrapper_factory(slave_factory)
slave_link = link_factory(*slave_args, **slave_kwargs)
"""
if cls.__init_slave__ in (None, WrapperMixin.__init_slave__):
raise TypeError('type %r does not implement the wraplet protocol' % getname(cls))
def wrapper_factory(slave_factory):
"""Factory to create a new class by wrapping ``slave_factory``"""
class Wraplet(cls): # pylint:disable=abstract-method
_slave_factory = staticmethod(slave_factory)
# Assign the wrapped attributes directly instead of
# using functools.wraps, as we may deal with arbitrarry
# class/callable combinations.
__doc__ = slave_factory.__doc__
# While the wrapped instance wraps the slave, the
# wrapper class wraps the slave factory. Any instance
# then just hides the class level attribute.
# Exposing __wrapped__ here allows introspection,such
# as inspect.signature, to pick up metadata.
__wrapped__ = slave_factory
# In Py3.X, objects without any annotations just provide an
# empty dict.
__annotations__ = getattr(slave_factory, '__annotations__', {})
def __init__(self, *slave_args, **slave_kwargs):
slave = self.__init_slave__(self._slave_factory, *slave_args, **slave_kwargs)
super(Wraplet, self).__init__(slave, *cls_args, **cls_kwargs)
__repr__ = cls.__wraplet_repr__
# swap places with our target so that both can be pickled/unpickled
Wraplet.__name__ = getname(slave_factory).split('.')[-1]
Wraplet.__qualname__ = getname(slave_factory)
Wraplet.__module__ = slave_factory.__module__
# this is enough for Py3.4+ to find the slave
slave_factory.__qualname__ = Wraplet.__qualname__ + '._slave_factory'
# ## This is an EVIL hack! Do not use use this at home unless you understand it! ##
# enable python2 lookup of the slave via its wrapper
# This allows to implicitly pickle slave objects which already support pickle,
# e.g. function and partial.
# python2 pickle performs the equivalent of getattr(sys.modules[obj.__module__, obj.__name__]
# which does not allow dotted name lookups. To work around this, we place the slave into the
# module, globally, using the qualified name *explicitly*. As qualified names are not valid identifiers,
# this will not create a collision unless someone tries to do the same trick.
if sys.version_info[:2] <= (3, 4):
# While 3.4 adds support for using __qualname__, that is *only* for protocol 4. Older
# protocols still require __name__. However, 3.4 *explicitly* disallows using dotted names,
# which defeats the obvious way of injecting the proper dotted name. Instead, an illegal name
# using : in place of . is used, which should also not conflict.
name_separator = '.' if sys.version_info[:2] != (3, 4) else ':'
# Make sure we actually register the correct entity
# Since we are only working with __name__, the slave could be defined
# in an inner scope. In this case, registering it in the global namespace
# may increase its lifetime, or replace an actual global slave of the
# same name.
# There are two cases we have to check here:
# slave = wraplet(slave)
# The slave already exists in the module namespace, with its __name__.
# The object with that name must be *identical* to the slave.
# @wraplet\ndef slave
# Neither slave nor Wrapper exist in the namespace yet (they are only bound *after*
# the wraplet returns). No object may exist with the same name.
if getattr(sys.modules[slave_factory.__module__], slave_factory.__name__, slave_factory) is slave_factory:
slave_factory.__name__ += name_separator + '_slave_factory'
setattr(sys.modules[slave_factory.__module__], slave_factory.__name__, slave_factory)
return Wraplet
return wrapper_factory
|
[
"def",
"wraplet",
"(",
"cls",
",",
"*",
"cls_args",
",",
"*",
"*",
"cls_kwargs",
")",
":",
"if",
"cls",
".",
"__init_slave__",
"in",
"(",
"None",
",",
"WrapperMixin",
".",
"__init_slave__",
")",
":",
"raise",
"TypeError",
"(",
"'type %r does not implement the wraplet protocol'",
"%",
"getname",
"(",
"cls",
")",
")",
"def",
"wrapper_factory",
"(",
"slave_factory",
")",
":",
"\"\"\"Factory to create a new class by wrapping ``slave_factory``\"\"\"",
"class",
"Wraplet",
"(",
"cls",
")",
":",
"# pylint:disable=abstract-method",
"_slave_factory",
"=",
"staticmethod",
"(",
"slave_factory",
")",
"# Assign the wrapped attributes directly instead of",
"# using functools.wraps, as we may deal with arbitrarry",
"# class/callable combinations.",
"__doc__",
"=",
"slave_factory",
".",
"__doc__",
"# While the wrapped instance wraps the slave, the",
"# wrapper class wraps the slave factory. Any instance",
"# then just hides the class level attribute.",
"# Exposing __wrapped__ here allows introspection,such",
"# as inspect.signature, to pick up metadata.",
"__wrapped__",
"=",
"slave_factory",
"# In Py3.X, objects without any annotations just provide an",
"# empty dict.",
"__annotations__",
"=",
"getattr",
"(",
"slave_factory",
",",
"'__annotations__'",
",",
"{",
"}",
")",
"def",
"__init__",
"(",
"self",
",",
"*",
"slave_args",
",",
"*",
"*",
"slave_kwargs",
")",
":",
"slave",
"=",
"self",
".",
"__init_slave__",
"(",
"self",
".",
"_slave_factory",
",",
"*",
"slave_args",
",",
"*",
"*",
"slave_kwargs",
")",
"super",
"(",
"Wraplet",
",",
"self",
")",
".",
"__init__",
"(",
"slave",
",",
"*",
"cls_args",
",",
"*",
"*",
"cls_kwargs",
")",
"__repr__",
"=",
"cls",
".",
"__wraplet_repr__",
"# swap places with our target so that both can be pickled/unpickled",
"Wraplet",
".",
"__name__",
"=",
"getname",
"(",
"slave_factory",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"Wraplet",
".",
"__qualname__",
"=",
"getname",
"(",
"slave_factory",
")",
"Wraplet",
".",
"__module__",
"=",
"slave_factory",
".",
"__module__",
"# this is enough for Py3.4+ to find the slave",
"slave_factory",
".",
"__qualname__",
"=",
"Wraplet",
".",
"__qualname__",
"+",
"'._slave_factory'",
"# ## This is an EVIL hack! Do not use use this at home unless you understand it! ##",
"# enable python2 lookup of the slave via its wrapper",
"# This allows to implicitly pickle slave objects which already support pickle,",
"# e.g. function and partial.",
"# python2 pickle performs the equivalent of getattr(sys.modules[obj.__module__, obj.__name__]",
"# which does not allow dotted name lookups. To work around this, we place the slave into the",
"# module, globally, using the qualified name *explicitly*. As qualified names are not valid identifiers,",
"# this will not create a collision unless someone tries to do the same trick.",
"if",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
"<=",
"(",
"3",
",",
"4",
")",
":",
"# While 3.4 adds support for using __qualname__, that is *only* for protocol 4. Older",
"# protocols still require __name__. However, 3.4 *explicitly* disallows using dotted names,",
"# which defeats the obvious way of injecting the proper dotted name. Instead, an illegal name",
"# using : in place of . is used, which should also not conflict.",
"name_separator",
"=",
"'.'",
"if",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
"!=",
"(",
"3",
",",
"4",
")",
"else",
"':'",
"# Make sure we actually register the correct entity",
"# Since we are only working with __name__, the slave could be defined",
"# in an inner scope. In this case, registering it in the global namespace",
"# may increase its lifetime, or replace an actual global slave of the",
"# same name.",
"# There are two cases we have to check here:",
"# slave = wraplet(slave)",
"# The slave already exists in the module namespace, with its __name__.",
"# The object with that name must be *identical* to the slave.",
"# @wraplet\\ndef slave",
"# Neither slave nor Wrapper exist in the namespace yet (they are only bound *after*",
"# the wraplet returns). No object may exist with the same name.",
"if",
"getattr",
"(",
"sys",
".",
"modules",
"[",
"slave_factory",
".",
"__module__",
"]",
",",
"slave_factory",
".",
"__name__",
",",
"slave_factory",
")",
"is",
"slave_factory",
":",
"slave_factory",
".",
"__name__",
"+=",
"name_separator",
"+",
"'_slave_factory'",
"setattr",
"(",
"sys",
".",
"modules",
"[",
"slave_factory",
".",
"__module__",
"]",
",",
"slave_factory",
".",
"__name__",
",",
"slave_factory",
")",
"return",
"Wraplet",
"return",
"wrapper_factory"
] |
Create a factory to produce a Wrapper from a slave factory
:param cls_args: positional arguments to provide to the Wrapper class
:param cls_kwargs: keyword arguments to provide to the Wrapper class
:return:
.. code:: python
cls_wrapper_factory = cls.wraplet(*cls_args, **cls_kwargs)
link_factory = cls_wrapper_factory(slave_factory)
slave_link = link_factory(*slave_args, **slave_kwargs)
|
[
"Create",
"a",
"factory",
"to",
"produce",
"a",
"Wrapper",
"from",
"a",
"slave",
"factory"
] |
4e17f9992b4780bd0d9309202e2847df640bffe8
|
https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/wrapper.py#L87-L164
|
245,426
|
ronaldguillen/wave
|
wave/authentication.py
|
BasicAuthentication.authenticate
|
def authenticate(self, request):
"""
Returns a `User` if a correct username and password have been supplied
using HTTP Basic authentication. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'basic':
return None
if len(auth) == 1:
msg = _('Invalid basic header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid basic header. Credentials string should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
try:
auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
except (TypeError, UnicodeDecodeError):
msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
raise exceptions.AuthenticationFailed(msg)
userid, password = auth_parts[0], auth_parts[2]
return self.authenticate_credentials(userid, password)
|
python
|
def authenticate(self, request):
"""
Returns a `User` if a correct username and password have been supplied
using HTTP Basic authentication. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'basic':
return None
if len(auth) == 1:
msg = _('Invalid basic header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid basic header. Credentials string should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
try:
auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
except (TypeError, UnicodeDecodeError):
msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
raise exceptions.AuthenticationFailed(msg)
userid, password = auth_parts[0], auth_parts[2]
return self.authenticate_credentials(userid, password)
|
[
"def",
"authenticate",
"(",
"self",
",",
"request",
")",
":",
"auth",
"=",
"get_authorization_header",
"(",
"request",
")",
".",
"split",
"(",
")",
"if",
"not",
"auth",
"or",
"auth",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"!=",
"b'basic'",
":",
"return",
"None",
"if",
"len",
"(",
"auth",
")",
"==",
"1",
":",
"msg",
"=",
"_",
"(",
"'Invalid basic header. No credentials provided.'",
")",
"raise",
"exceptions",
".",
"AuthenticationFailed",
"(",
"msg",
")",
"elif",
"len",
"(",
"auth",
")",
">",
"2",
":",
"msg",
"=",
"_",
"(",
"'Invalid basic header. Credentials string should not contain spaces.'",
")",
"raise",
"exceptions",
".",
"AuthenticationFailed",
"(",
"msg",
")",
"try",
":",
"auth_parts",
"=",
"base64",
".",
"b64decode",
"(",
"auth",
"[",
"1",
"]",
")",
".",
"decode",
"(",
"HTTP_HEADER_ENCODING",
")",
".",
"partition",
"(",
"':'",
")",
"except",
"(",
"TypeError",
",",
"UnicodeDecodeError",
")",
":",
"msg",
"=",
"_",
"(",
"'Invalid basic header. Credentials not correctly base64 encoded.'",
")",
"raise",
"exceptions",
".",
"AuthenticationFailed",
"(",
"msg",
")",
"userid",
",",
"password",
"=",
"auth_parts",
"[",
"0",
"]",
",",
"auth_parts",
"[",
"2",
"]",
"return",
"self",
".",
"authenticate_credentials",
"(",
"userid",
",",
"password",
")"
] |
Returns a `User` if a correct username and password have been supplied
using HTTP Basic authentication. Otherwise returns `None`.
|
[
"Returns",
"a",
"User",
"if",
"a",
"correct",
"username",
"and",
"password",
"have",
"been",
"supplied",
"using",
"HTTP",
"Basic",
"authentication",
".",
"Otherwise",
"returns",
"None",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/authentication.py#L61-L85
|
245,427
|
ronaldguillen/wave
|
wave/authentication.py
|
BasicAuthentication.authenticate_credentials
|
def authenticate_credentials(self, userid, password):
"""
Authenticate the userid and password against username and password.
"""
credentials = {
get_user_model().USERNAME_FIELD: userid,
'password': password
}
user = authenticate(**credentials)
if user is None:
raise exceptions.AuthenticationFailed(_('Invalid username/password.'))
if not user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
return (user, None)
|
python
|
def authenticate_credentials(self, userid, password):
"""
Authenticate the userid and password against username and password.
"""
credentials = {
get_user_model().USERNAME_FIELD: userid,
'password': password
}
user = authenticate(**credentials)
if user is None:
raise exceptions.AuthenticationFailed(_('Invalid username/password.'))
if not user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
return (user, None)
|
[
"def",
"authenticate_credentials",
"(",
"self",
",",
"userid",
",",
"password",
")",
":",
"credentials",
"=",
"{",
"get_user_model",
"(",
")",
".",
"USERNAME_FIELD",
":",
"userid",
",",
"'password'",
":",
"password",
"}",
"user",
"=",
"authenticate",
"(",
"*",
"*",
"credentials",
")",
"if",
"user",
"is",
"None",
":",
"raise",
"exceptions",
".",
"AuthenticationFailed",
"(",
"_",
"(",
"'Invalid username/password.'",
")",
")",
"if",
"not",
"user",
".",
"is_active",
":",
"raise",
"exceptions",
".",
"AuthenticationFailed",
"(",
"_",
"(",
"'User inactive or deleted.'",
")",
")",
"return",
"(",
"user",
",",
"None",
")"
] |
Authenticate the userid and password against username and password.
|
[
"Authenticate",
"the",
"userid",
"and",
"password",
"against",
"username",
"and",
"password",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/authentication.py#L87-L103
|
245,428
|
ronaldguillen/wave
|
wave/authentication.py
|
SessionAuthentication.enforce_csrf
|
def enforce_csrf(self, request):
"""
Enforce CSRF validation for session based authentication.
"""
reason = CSRFCheck().process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
|
python
|
def enforce_csrf(self, request):
"""
Enforce CSRF validation for session based authentication.
"""
reason = CSRFCheck().process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
|
[
"def",
"enforce_csrf",
"(",
"self",
",",
"request",
")",
":",
"reason",
"=",
"CSRFCheck",
"(",
")",
".",
"process_view",
"(",
"request",
",",
"None",
",",
"(",
")",
",",
"{",
"}",
")",
"if",
"reason",
":",
"# CSRF failed, bail with explicit error message",
"raise",
"exceptions",
".",
"PermissionDenied",
"(",
"'CSRF Failed: %s'",
"%",
"reason",
")"
] |
Enforce CSRF validation for session based authentication.
|
[
"Enforce",
"CSRF",
"validation",
"for",
"session",
"based",
"authentication",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/authentication.py#L132-L139
|
245,429
|
fusionapp/fusion-util
|
fusion_util/enums.py
|
filter_enum
|
def filter_enum(pred, enum):
"""
Create a new enumeration containing only items filtered from another
enumeration.
Hidden enum items in the original enumeration are excluded.
:type pred: ``Callable[[`EnumItem`], bool]``
:param pred: Predicate that will keep items for which the result is true.
:type enum: Enum
:param enum: Enumeration to filter.
:rtype: Enum
:return: New filtered enumeration.
"""
def _items():
for item in enum:
yield EnumItem(
item.value,
item.desc,
not pred(item),
**item._extra)
return Enum('Filtered from {!r}'.format(enum), list(_items()))
|
python
|
def filter_enum(pred, enum):
"""
Create a new enumeration containing only items filtered from another
enumeration.
Hidden enum items in the original enumeration are excluded.
:type pred: ``Callable[[`EnumItem`], bool]``
:param pred: Predicate that will keep items for which the result is true.
:type enum: Enum
:param enum: Enumeration to filter.
:rtype: Enum
:return: New filtered enumeration.
"""
def _items():
for item in enum:
yield EnumItem(
item.value,
item.desc,
not pred(item),
**item._extra)
return Enum('Filtered from {!r}'.format(enum), list(_items()))
|
[
"def",
"filter_enum",
"(",
"pred",
",",
"enum",
")",
":",
"def",
"_items",
"(",
")",
":",
"for",
"item",
"in",
"enum",
":",
"yield",
"EnumItem",
"(",
"item",
".",
"value",
",",
"item",
".",
"desc",
",",
"not",
"pred",
"(",
"item",
")",
",",
"*",
"*",
"item",
".",
"_extra",
")",
"return",
"Enum",
"(",
"'Filtered from {!r}'",
".",
"format",
"(",
"enum",
")",
",",
"list",
"(",
"_items",
"(",
")",
")",
")"
] |
Create a new enumeration containing only items filtered from another
enumeration.
Hidden enum items in the original enumeration are excluded.
:type pred: ``Callable[[`EnumItem`], bool]``
:param pred: Predicate that will keep items for which the result is true.
:type enum: Enum
:param enum: Enumeration to filter.
:rtype: Enum
:return: New filtered enumeration.
|
[
"Create",
"a",
"new",
"enumeration",
"containing",
"only",
"items",
"filtered",
"from",
"another",
"enumeration",
"."
] |
089c525799926c8b8bf1117ab22ed055dc99c7e6
|
https://github.com/fusionapp/fusion-util/blob/089c525799926c8b8bf1117ab22ed055dc99c7e6/fusion_util/enums.py#L299-L320
|
245,430
|
fusionapp/fusion-util
|
fusion_util/enums.py
|
Enum.from_pairs
|
def from_pairs(cls, doc, pairs):
"""
Construct an enumeration from an iterable of pairs.
:param doc: See `Enum.__init__`.
:type pairs: ``Iterable[Tuple[unicode, unicode]]``
:param pairs: Iterable to construct the enumeration from.
:rtype: Enum
"""
values = (EnumItem(value, desc) for value, desc in pairs)
return cls(doc=doc, values=values)
|
python
|
def from_pairs(cls, doc, pairs):
"""
Construct an enumeration from an iterable of pairs.
:param doc: See `Enum.__init__`.
:type pairs: ``Iterable[Tuple[unicode, unicode]]``
:param pairs: Iterable to construct the enumeration from.
:rtype: Enum
"""
values = (EnumItem(value, desc) for value, desc in pairs)
return cls(doc=doc, values=values)
|
[
"def",
"from_pairs",
"(",
"cls",
",",
"doc",
",",
"pairs",
")",
":",
"values",
"=",
"(",
"EnumItem",
"(",
"value",
",",
"desc",
")",
"for",
"value",
",",
"desc",
"in",
"pairs",
")",
"return",
"cls",
"(",
"doc",
"=",
"doc",
",",
"values",
"=",
"values",
")"
] |
Construct an enumeration from an iterable of pairs.
:param doc: See `Enum.__init__`.
:type pairs: ``Iterable[Tuple[unicode, unicode]]``
:param pairs: Iterable to construct the enumeration from.
:rtype: Enum
|
[
"Construct",
"an",
"enumeration",
"from",
"an",
"iterable",
"of",
"pairs",
"."
] |
089c525799926c8b8bf1117ab22ed055dc99c7e6
|
https://github.com/fusionapp/fusion-util/blob/089c525799926c8b8bf1117ab22ed055dc99c7e6/fusion_util/enums.py#L69-L79
|
245,431
|
fusionapp/fusion-util
|
fusion_util/enums.py
|
Enum.get
|
def get(self, value):
"""
Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem
"""
_nothing = object()
item = self._values.get(value, _nothing)
if item is _nothing:
raise InvalidEnumItem(value)
return item
|
python
|
def get(self, value):
"""
Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem
"""
_nothing = object()
item = self._values.get(value, _nothing)
if item is _nothing:
raise InvalidEnumItem(value)
return item
|
[
"def",
"get",
"(",
"self",
",",
"value",
")",
":",
"_nothing",
"=",
"object",
"(",
")",
"item",
"=",
"self",
".",
"_values",
".",
"get",
"(",
"value",
",",
"_nothing",
")",
"if",
"item",
"is",
"_nothing",
":",
"raise",
"InvalidEnumItem",
"(",
"value",
")",
"return",
"item"
] |
Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem
|
[
"Get",
"an",
"enumeration",
"item",
"for",
"an",
"enumeration",
"value",
"."
] |
089c525799926c8b8bf1117ab22ed055dc99c7e6
|
https://github.com/fusionapp/fusion-util/blob/089c525799926c8b8bf1117ab22ed055dc99c7e6/fusion_util/enums.py#L89-L102
|
245,432
|
fusionapp/fusion-util
|
fusion_util/enums.py
|
Enum.extra
|
def extra(self, value, extra_name, default=None):
"""
Get the additional enumeration value for ``extra_name``.
:param unicode value: Enumeration value.
:param str extra_name: Extra name.
:param default: Default value in the case ``extra_name`` doesn't exist.
"""
try:
return self.get(value).get(extra_name, default)
except InvalidEnumItem:
return default
|
python
|
def extra(self, value, extra_name, default=None):
"""
Get the additional enumeration value for ``extra_name``.
:param unicode value: Enumeration value.
:param str extra_name: Extra name.
:param default: Default value in the case ``extra_name`` doesn't exist.
"""
try:
return self.get(value).get(extra_name, default)
except InvalidEnumItem:
return default
|
[
"def",
"extra",
"(",
"self",
",",
"value",
",",
"extra_name",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"get",
"(",
"value",
")",
".",
"get",
"(",
"extra_name",
",",
"default",
")",
"except",
"InvalidEnumItem",
":",
"return",
"default"
] |
Get the additional enumeration value for ``extra_name``.
:param unicode value: Enumeration value.
:param str extra_name: Extra name.
:param default: Default value in the case ``extra_name`` doesn't exist.
|
[
"Get",
"the",
"additional",
"enumeration",
"value",
"for",
"extra_name",
"."
] |
089c525799926c8b8bf1117ab22ed055dc99c7e6
|
https://github.com/fusionapp/fusion-util/blob/089c525799926c8b8bf1117ab22ed055dc99c7e6/fusion_util/enums.py#L123-L134
|
245,433
|
fusionapp/fusion-util
|
fusion_util/enums.py
|
Enum.find_all
|
def find_all(self, **names):
"""
Find all items with matching extra values.
:param \*\*names: Extra values to match.
:rtype: ``Iterable[`EnumItem`]``
"""
values = names.items()
if len(values) != 1:
raise ValueError('Only one query is allowed at a time')
name, value = values[0]
for item in self:
if item.get(name) == value:
yield item
|
python
|
def find_all(self, **names):
"""
Find all items with matching extra values.
:param \*\*names: Extra values to match.
:rtype: ``Iterable[`EnumItem`]``
"""
values = names.items()
if len(values) != 1:
raise ValueError('Only one query is allowed at a time')
name, value = values[0]
for item in self:
if item.get(name) == value:
yield item
|
[
"def",
"find_all",
"(",
"self",
",",
"*",
"*",
"names",
")",
":",
"values",
"=",
"names",
".",
"items",
"(",
")",
"if",
"len",
"(",
"values",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'Only one query is allowed at a time'",
")",
"name",
",",
"value",
"=",
"values",
"[",
"0",
"]",
"for",
"item",
"in",
"self",
":",
"if",
"item",
".",
"get",
"(",
"name",
")",
"==",
"value",
":",
"yield",
"item"
] |
Find all items with matching extra values.
:param \*\*names: Extra values to match.
:rtype: ``Iterable[`EnumItem`]``
|
[
"Find",
"all",
"items",
"with",
"matching",
"extra",
"values",
"."
] |
089c525799926c8b8bf1117ab22ed055dc99c7e6
|
https://github.com/fusionapp/fusion-util/blob/089c525799926c8b8bf1117ab22ed055dc99c7e6/fusion_util/enums.py#L156-L169
|
245,434
|
SkyLothar/shcmd
|
shcmd/utils.py
|
expand_args
|
def expand_args(cmd_args):
"""split command args to args list
returns a list of args
:param cmd_args: command args, can be tuple, list or str
"""
if isinstance(cmd_args, (tuple, list)):
args_list = list(cmd_args)
else:
args_list = shlex.split(cmd_args)
return args_list
|
python
|
def expand_args(cmd_args):
"""split command args to args list
returns a list of args
:param cmd_args: command args, can be tuple, list or str
"""
if isinstance(cmd_args, (tuple, list)):
args_list = list(cmd_args)
else:
args_list = shlex.split(cmd_args)
return args_list
|
[
"def",
"expand_args",
"(",
"cmd_args",
")",
":",
"if",
"isinstance",
"(",
"cmd_args",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"args_list",
"=",
"list",
"(",
"cmd_args",
")",
"else",
":",
"args_list",
"=",
"shlex",
".",
"split",
"(",
"cmd_args",
")",
"return",
"args_list"
] |
split command args to args list
returns a list of args
:param cmd_args: command args, can be tuple, list or str
|
[
"split",
"command",
"args",
"to",
"args",
"list",
"returns",
"a",
"list",
"of",
"args"
] |
d8cad6311a4da7ef09f3419c86b58e30388b7ee3
|
https://github.com/SkyLothar/shcmd/blob/d8cad6311a4da7ef09f3419c86b58e30388b7ee3/shcmd/utils.py#L6-L16
|
245,435
|
etcher-be/emiz
|
emiz/avwx/service.py
|
get_service
|
def get_service(station: str) -> Service:
"""
Returns the preferred service for a given station
"""
for prefix in PREFERRED:
if station.startswith(prefix):
return PREFERRED[prefix] # type: ignore
return NOAA
|
python
|
def get_service(station: str) -> Service:
"""
Returns the preferred service for a given station
"""
for prefix in PREFERRED:
if station.startswith(prefix):
return PREFERRED[prefix] # type: ignore
return NOAA
|
[
"def",
"get_service",
"(",
"station",
":",
"str",
")",
"->",
"Service",
":",
"for",
"prefix",
"in",
"PREFERRED",
":",
"if",
"station",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"PREFERRED",
"[",
"prefix",
"]",
"# type: ignore",
"return",
"NOAA"
] |
Returns the preferred service for a given station
|
[
"Returns",
"the",
"preferred",
"service",
"for",
"a",
"given",
"station"
] |
1c3e32711921d7e600e85558ffe5d337956372de
|
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/service.py#L143-L150
|
245,436
|
etcher-be/emiz
|
emiz/avwx/service.py
|
Service.make_err
|
def make_err(self, body: str, key: str = 'report path') -> InvalidRequest:
"""
Returns an InvalidRequest exception with formatted error message
"""
msg = f'Could not find {key} in {self.__class__.__name__} response\n'
return InvalidRequest(msg + body)
|
python
|
def make_err(self, body: str, key: str = 'report path') -> InvalidRequest:
"""
Returns an InvalidRequest exception with formatted error message
"""
msg = f'Could not find {key} in {self.__class__.__name__} response\n'
return InvalidRequest(msg + body)
|
[
"def",
"make_err",
"(",
"self",
",",
"body",
":",
"str",
",",
"key",
":",
"str",
"=",
"'report path'",
")",
"->",
"InvalidRequest",
":",
"msg",
"=",
"f'Could not find {key} in {self.__class__.__name__} response\\n'",
"return",
"InvalidRequest",
"(",
"msg",
"+",
"body",
")"
] |
Returns an InvalidRequest exception with formatted error message
|
[
"Returns",
"an",
"InvalidRequest",
"exception",
"with",
"formatted",
"error",
"message"
] |
1c3e32711921d7e600e85558ffe5d337956372de
|
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/service.py#L27-L32
|
245,437
|
etcher-be/emiz
|
emiz/avwx/service.py
|
Service.fetch
|
def fetch(self, station: str) -> str:
"""
Fetches a report string from the service
"""
valid_station(station)
try:
resp = getattr(requests, self.method.lower())(self.url.format(self.rtype, station))
if resp.status_code != 200:
raise SourceError(f'{self.__class__.__name__} server returned {resp.status_code}')
except requests.exceptions.ConnectionError:
raise ConnectionError(f'Unable to connect to {self.__class__.__name__} server')
report = self._extract(resp.text, station)
# This split join replaces all *whitespace elements with a single space
return ' '.join(report.split())
|
python
|
def fetch(self, station: str) -> str:
"""
Fetches a report string from the service
"""
valid_station(station)
try:
resp = getattr(requests, self.method.lower())(self.url.format(self.rtype, station))
if resp.status_code != 200:
raise SourceError(f'{self.__class__.__name__} server returned {resp.status_code}')
except requests.exceptions.ConnectionError:
raise ConnectionError(f'Unable to connect to {self.__class__.__name__} server')
report = self._extract(resp.text, station)
# This split join replaces all *whitespace elements with a single space
return ' '.join(report.split())
|
[
"def",
"fetch",
"(",
"self",
",",
"station",
":",
"str",
")",
"->",
"str",
":",
"valid_station",
"(",
"station",
")",
"try",
":",
"resp",
"=",
"getattr",
"(",
"requests",
",",
"self",
".",
"method",
".",
"lower",
"(",
")",
")",
"(",
"self",
".",
"url",
".",
"format",
"(",
"self",
".",
"rtype",
",",
"station",
")",
")",
"if",
"resp",
".",
"status_code",
"!=",
"200",
":",
"raise",
"SourceError",
"(",
"f'{self.__class__.__name__} server returned {resp.status_code}'",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
":",
"raise",
"ConnectionError",
"(",
"f'Unable to connect to {self.__class__.__name__} server'",
")",
"report",
"=",
"self",
".",
"_extract",
"(",
"resp",
".",
"text",
",",
"station",
")",
"# This split join replaces all *whitespace elements with a single space",
"return",
"' '",
".",
"join",
"(",
"report",
".",
"split",
"(",
")",
")"
] |
Fetches a report string from the service
|
[
"Fetches",
"a",
"report",
"string",
"from",
"the",
"service"
] |
1c3e32711921d7e600e85558ffe5d337956372de
|
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/service.py#L40-L53
|
245,438
|
etcher-be/emiz
|
emiz/avwx/service.py
|
NOAA._extract
|
def _extract(self, raw: str, station: str = None) -> str:
"""
Extracts the raw_report element from XML response
"""
resp = parsexml(raw)
try:
report = resp['response']['data'][self.rtype.upper()]
except KeyError:
raise self.make_err(raw)
# Find report string
if isinstance(report, dict):
report = report['raw_text']
elif isinstance(report, list) and report:
report = report[0]['raw_text']
else:
raise self.make_err(raw, '"raw_text"')
# Remove excess leading and trailing data
for item in (self.rtype.upper(), 'SPECI'):
if report.startswith(item + ' '):
report = report[len(item) + 1:]
return report
|
python
|
def _extract(self, raw: str, station: str = None) -> str:
"""
Extracts the raw_report element from XML response
"""
resp = parsexml(raw)
try:
report = resp['response']['data'][self.rtype.upper()]
except KeyError:
raise self.make_err(raw)
# Find report string
if isinstance(report, dict):
report = report['raw_text']
elif isinstance(report, list) and report:
report = report[0]['raw_text']
else:
raise self.make_err(raw, '"raw_text"')
# Remove excess leading and trailing data
for item in (self.rtype.upper(), 'SPECI'):
if report.startswith(item + ' '):
report = report[len(item) + 1:]
return report
|
[
"def",
"_extract",
"(",
"self",
",",
"raw",
":",
"str",
",",
"station",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"resp",
"=",
"parsexml",
"(",
"raw",
")",
"try",
":",
"report",
"=",
"resp",
"[",
"'response'",
"]",
"[",
"'data'",
"]",
"[",
"self",
".",
"rtype",
".",
"upper",
"(",
")",
"]",
"except",
"KeyError",
":",
"raise",
"self",
".",
"make_err",
"(",
"raw",
")",
"# Find report string",
"if",
"isinstance",
"(",
"report",
",",
"dict",
")",
":",
"report",
"=",
"report",
"[",
"'raw_text'",
"]",
"elif",
"isinstance",
"(",
"report",
",",
"list",
")",
"and",
"report",
":",
"report",
"=",
"report",
"[",
"0",
"]",
"[",
"'raw_text'",
"]",
"else",
":",
"raise",
"self",
".",
"make_err",
"(",
"raw",
",",
"'\"raw_text\"'",
")",
"# Remove excess leading and trailing data",
"for",
"item",
"in",
"(",
"self",
".",
"rtype",
".",
"upper",
"(",
")",
",",
"'SPECI'",
")",
":",
"if",
"report",
".",
"startswith",
"(",
"item",
"+",
"' '",
")",
":",
"report",
"=",
"report",
"[",
"len",
"(",
"item",
")",
"+",
"1",
":",
"]",
"return",
"report"
] |
Extracts the raw_report element from XML response
|
[
"Extracts",
"the",
"raw_report",
"element",
"from",
"XML",
"response"
] |
1c3e32711921d7e600e85558ffe5d337956372de
|
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/service.py#L70-L90
|
245,439
|
etcher-be/emiz
|
emiz/avwx/service.py
|
AMO._extract
|
def _extract(self, raw: str, station: str = None) -> str:
"""
Extracts the report message from XML response
"""
resp = parsexml(raw)
try:
report = resp['response']['body']['items']['item'][self.rtype.lower() + 'Msg']
except KeyError:
raise self.make_err(raw)
# Replace line breaks
report = report.replace('\n', '')
# Remove excess leading and trailing data
for item in (self.rtype.upper(), 'SPECI'):
if report.startswith(item + ' '):
report = report[len(item) + 1:]
report = report.rstrip('=')
# Make every element single-spaced and stripped
return ' '.join(report.split())
|
python
|
def _extract(self, raw: str, station: str = None) -> str:
"""
Extracts the report message from XML response
"""
resp = parsexml(raw)
try:
report = resp['response']['body']['items']['item'][self.rtype.lower() + 'Msg']
except KeyError:
raise self.make_err(raw)
# Replace line breaks
report = report.replace('\n', '')
# Remove excess leading and trailing data
for item in (self.rtype.upper(), 'SPECI'):
if report.startswith(item + ' '):
report = report[len(item) + 1:]
report = report.rstrip('=')
# Make every element single-spaced and stripped
return ' '.join(report.split())
|
[
"def",
"_extract",
"(",
"self",
",",
"raw",
":",
"str",
",",
"station",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"resp",
"=",
"parsexml",
"(",
"raw",
")",
"try",
":",
"report",
"=",
"resp",
"[",
"'response'",
"]",
"[",
"'body'",
"]",
"[",
"'items'",
"]",
"[",
"'item'",
"]",
"[",
"self",
".",
"rtype",
".",
"lower",
"(",
")",
"+",
"'Msg'",
"]",
"except",
"KeyError",
":",
"raise",
"self",
".",
"make_err",
"(",
"raw",
")",
"# Replace line breaks",
"report",
"=",
"report",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"# Remove excess leading and trailing data",
"for",
"item",
"in",
"(",
"self",
".",
"rtype",
".",
"upper",
"(",
")",
",",
"'SPECI'",
")",
":",
"if",
"report",
".",
"startswith",
"(",
"item",
"+",
"' '",
")",
":",
"report",
"=",
"report",
"[",
"len",
"(",
"item",
")",
"+",
"1",
":",
"]",
"report",
"=",
"report",
".",
"rstrip",
"(",
"'='",
")",
"# Make every element single-spaced and stripped",
"return",
"' '",
".",
"join",
"(",
"report",
".",
"split",
"(",
")",
")"
] |
Extracts the report message from XML response
|
[
"Extracts",
"the",
"report",
"message",
"from",
"XML",
"response"
] |
1c3e32711921d7e600e85558ffe5d337956372de
|
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/service.py#L100-L117
|
245,440
|
etcher-be/emiz
|
emiz/avwx/service.py
|
MAC._extract
|
def _extract(self, raw: str, station: str) -> str: # type: ignore
"""
Extracts the reports message using string finding
"""
report = raw[raw.find(station.upper() + ' '):]
report = report[:report.find(' =')]
return report
|
python
|
def _extract(self, raw: str, station: str) -> str: # type: ignore
"""
Extracts the reports message using string finding
"""
report = raw[raw.find(station.upper() + ' '):]
report = report[:report.find(' =')]
return report
|
[
"def",
"_extract",
"(",
"self",
",",
"raw",
":",
"str",
",",
"station",
":",
"str",
")",
"->",
"str",
":",
"# type: ignore",
"report",
"=",
"raw",
"[",
"raw",
".",
"find",
"(",
"station",
".",
"upper",
"(",
")",
"+",
"' '",
")",
":",
"]",
"report",
"=",
"report",
"[",
":",
"report",
".",
"find",
"(",
"' ='",
")",
"]",
"return",
"report"
] |
Extracts the reports message using string finding
|
[
"Extracts",
"the",
"reports",
"message",
"using",
"string",
"finding"
] |
1c3e32711921d7e600e85558ffe5d337956372de
|
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/service.py#L128-L134
|
245,441
|
etcher-be/emiz
|
emiz/weather/mizfile/mizfile_set_metar.py
|
set_weather_from_metar
|
def set_weather_from_metar(
metar: typing.Union[Metar.Metar, str],
in_file: typing.Union[str, Path],
out_file: typing.Union[str, Path] = None
) -> typing.Tuple[typing.Union[str, None], typing.Union[str, None]]:
"""
Applies the weather from a METAR object to a MIZ file
Args:
metar: metar object
in_file: path to MIZ file
out_file: path to output MIZ file (will default to in_file)
Returns: tuple of error, success
"""
error, metar = custom_metar.CustomMetar.get_metar(metar)
if error:
return error, None
if metar:
LOGGER.debug('METAR: %s', metar.code)
in_file = elib.path.ensure_file(in_file)
if out_file is None:
out_file = in_file
else:
out_file = elib.path.ensure_file(out_file, must_exist=False)
LOGGER.debug('applying metar: %s -> %s', in_file, out_file)
try:
LOGGER.debug('building MissionWeather')
_mission_weather = mission_weather.MissionWeather(metar)
with Miz(str(in_file)) as miz:
_mission_weather.apply_to_miz(miz)
miz.zip(str(out_file))
return None, f'successfully applied METAR to {in_file}'
except ValueError:
error = f'Unable to apply METAR string to the mission.\n' \
f'This is most likely due to a freak value, this feature is still experimental.\n' \
f'I will fix it ASAP !'
return error, None
|
python
|
def set_weather_from_metar(
metar: typing.Union[Metar.Metar, str],
in_file: typing.Union[str, Path],
out_file: typing.Union[str, Path] = None
) -> typing.Tuple[typing.Union[str, None], typing.Union[str, None]]:
"""
Applies the weather from a METAR object to a MIZ file
Args:
metar: metar object
in_file: path to MIZ file
out_file: path to output MIZ file (will default to in_file)
Returns: tuple of error, success
"""
error, metar = custom_metar.CustomMetar.get_metar(metar)
if error:
return error, None
if metar:
LOGGER.debug('METAR: %s', metar.code)
in_file = elib.path.ensure_file(in_file)
if out_file is None:
out_file = in_file
else:
out_file = elib.path.ensure_file(out_file, must_exist=False)
LOGGER.debug('applying metar: %s -> %s', in_file, out_file)
try:
LOGGER.debug('building MissionWeather')
_mission_weather = mission_weather.MissionWeather(metar)
with Miz(str(in_file)) as miz:
_mission_weather.apply_to_miz(miz)
miz.zip(str(out_file))
return None, f'successfully applied METAR to {in_file}'
except ValueError:
error = f'Unable to apply METAR string to the mission.\n' \
f'This is most likely due to a freak value, this feature is still experimental.\n' \
f'I will fix it ASAP !'
return error, None
|
[
"def",
"set_weather_from_metar",
"(",
"metar",
":",
"typing",
".",
"Union",
"[",
"Metar",
".",
"Metar",
",",
"str",
"]",
",",
"in_file",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"out_file",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"Path",
"]",
"=",
"None",
")",
"->",
"typing",
".",
"Tuple",
"[",
"typing",
".",
"Union",
"[",
"str",
",",
"None",
"]",
",",
"typing",
".",
"Union",
"[",
"str",
",",
"None",
"]",
"]",
":",
"error",
",",
"metar",
"=",
"custom_metar",
".",
"CustomMetar",
".",
"get_metar",
"(",
"metar",
")",
"if",
"error",
":",
"return",
"error",
",",
"None",
"if",
"metar",
":",
"LOGGER",
".",
"debug",
"(",
"'METAR: %s'",
",",
"metar",
".",
"code",
")",
"in_file",
"=",
"elib",
".",
"path",
".",
"ensure_file",
"(",
"in_file",
")",
"if",
"out_file",
"is",
"None",
":",
"out_file",
"=",
"in_file",
"else",
":",
"out_file",
"=",
"elib",
".",
"path",
".",
"ensure_file",
"(",
"out_file",
",",
"must_exist",
"=",
"False",
")",
"LOGGER",
".",
"debug",
"(",
"'applying metar: %s -> %s'",
",",
"in_file",
",",
"out_file",
")",
"try",
":",
"LOGGER",
".",
"debug",
"(",
"'building MissionWeather'",
")",
"_mission_weather",
"=",
"mission_weather",
".",
"MissionWeather",
"(",
"metar",
")",
"with",
"Miz",
"(",
"str",
"(",
"in_file",
")",
")",
"as",
"miz",
":",
"_mission_weather",
".",
"apply_to_miz",
"(",
"miz",
")",
"miz",
".",
"zip",
"(",
"str",
"(",
"out_file",
")",
")",
"return",
"None",
",",
"f'successfully applied METAR to {in_file}'",
"except",
"ValueError",
":",
"error",
"=",
"f'Unable to apply METAR string to the mission.\\n'",
"f'This is most likely due to a freak value, this feature is still experimental.\\n'",
"f'I will fix it ASAP !'",
"return",
"error",
",",
"None"
] |
Applies the weather from a METAR object to a MIZ file
Args:
metar: metar object
in_file: path to MIZ file
out_file: path to output MIZ file (will default to in_file)
Returns: tuple of error, success
|
[
"Applies",
"the",
"weather",
"from",
"a",
"METAR",
"object",
"to",
"a",
"MIZ",
"file"
] |
1c3e32711921d7e600e85558ffe5d337956372de
|
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/weather/mizfile/mizfile_set_metar.py#L18-L63
|
245,442
|
bwesterb/tkbd
|
src/state.py
|
State._pull_schedule_loop
|
def _pull_schedule_loop(self):
""" Called every 16 minutes to pull a new version of the schedule """
try:
self.pull_schedule()
delay = 16*60
except ScheduleError, e:
self.l.exception("ScheduleError while pulling schedule. "+
"Retrying in 5m")
delay = 5*60
if not self.running:
return
self.scheduler.plan(time.time() + delay, self._pull_schedule_loop)
|
python
|
def _pull_schedule_loop(self):
""" Called every 16 minutes to pull a new version of the schedule """
try:
self.pull_schedule()
delay = 16*60
except ScheduleError, e:
self.l.exception("ScheduleError while pulling schedule. "+
"Retrying in 5m")
delay = 5*60
if not self.running:
return
self.scheduler.plan(time.time() + delay, self._pull_schedule_loop)
|
[
"def",
"_pull_schedule_loop",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"pull_schedule",
"(",
")",
"delay",
"=",
"16",
"*",
"60",
"except",
"ScheduleError",
",",
"e",
":",
"self",
".",
"l",
".",
"exception",
"(",
"\"ScheduleError while pulling schedule. \"",
"+",
"\"Retrying in 5m\"",
")",
"delay",
"=",
"5",
"*",
"60",
"if",
"not",
"self",
".",
"running",
":",
"return",
"self",
".",
"scheduler",
".",
"plan",
"(",
"time",
".",
"time",
"(",
")",
"+",
"delay",
",",
"self",
".",
"_pull_schedule_loop",
")"
] |
Called every 16 minutes to pull a new version of the schedule
|
[
"Called",
"every",
"16",
"minutes",
"to",
"pull",
"a",
"new",
"version",
"of",
"the",
"schedule"
] |
fcf16977d38a93fe9b7fa198513007ab9921b650
|
https://github.com/bwesterb/tkbd/blob/fcf16977d38a93fe9b7fa198513007ab9921b650/src/state.py#L75-L86
|
245,443
|
matthewdeanmartin/jiggle_version
|
jiggle_version/jiggle_class.py
|
JiggleVersion.jiggle_source_code
|
def jiggle_source_code(self): # type: () ->int
"""
Updates version of central package
"""
changed = 0
for file_name in self.file_inventory.source_files:
to_write = []
# self.create_missing(file_name, file_name)
if not os.path.isfile(file_name):
continue
all_source = self.file_opener.read_this(file_name)
if "__version_info__" in all_source:
logger.warning("We have __version_info__ to sync up.")
# raise TypeError()
with self.file_opener.open_this(file_name, "r") as infile:
for line in infile:
leading_white = self.leading_whitespace(line)
version, version_token = dunder_version.find_in_line(line)
if version:
simplified_line = dunder_version.simplify_line(
line, keep_comma=True
)
if simplified_line.strip(" \t\n").endswith(","):
comma = ","
else:
comma = ""
if simplified_line.strip(" \t\n").startswith(","):
start_comma = ","
else:
start_comma = ""
to_write.append(
'{0}{1}{2} = "{3}"{4}{5}\n'.format(
start_comma,
leading_white,
version_token,
unicode(self.version_to_write()),
comma,
self.signature,
)
)
else:
to_write.append(line)
check(self.file_opener.open_this(file_name, "r").read(), "".join(to_write))
with open(file_name, "w") as outfile:
outfile.writelines(to_write)
changed += 1
return changed
|
python
|
def jiggle_source_code(self): # type: () ->int
"""
Updates version of central package
"""
changed = 0
for file_name in self.file_inventory.source_files:
to_write = []
# self.create_missing(file_name, file_name)
if not os.path.isfile(file_name):
continue
all_source = self.file_opener.read_this(file_name)
if "__version_info__" in all_source:
logger.warning("We have __version_info__ to sync up.")
# raise TypeError()
with self.file_opener.open_this(file_name, "r") as infile:
for line in infile:
leading_white = self.leading_whitespace(line)
version, version_token = dunder_version.find_in_line(line)
if version:
simplified_line = dunder_version.simplify_line(
line, keep_comma=True
)
if simplified_line.strip(" \t\n").endswith(","):
comma = ","
else:
comma = ""
if simplified_line.strip(" \t\n").startswith(","):
start_comma = ","
else:
start_comma = ""
to_write.append(
'{0}{1}{2} = "{3}"{4}{5}\n'.format(
start_comma,
leading_white,
version_token,
unicode(self.version_to_write()),
comma,
self.signature,
)
)
else:
to_write.append(line)
check(self.file_opener.open_this(file_name, "r").read(), "".join(to_write))
with open(file_name, "w") as outfile:
outfile.writelines(to_write)
changed += 1
return changed
|
[
"def",
"jiggle_source_code",
"(",
"self",
")",
":",
"# type: () ->int",
"changed",
"=",
"0",
"for",
"file_name",
"in",
"self",
".",
"file_inventory",
".",
"source_files",
":",
"to_write",
"=",
"[",
"]",
"# self.create_missing(file_name, file_name)",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_name",
")",
":",
"continue",
"all_source",
"=",
"self",
".",
"file_opener",
".",
"read_this",
"(",
"file_name",
")",
"if",
"\"__version_info__\"",
"in",
"all_source",
":",
"logger",
".",
"warning",
"(",
"\"We have __version_info__ to sync up.\"",
")",
"# raise TypeError()",
"with",
"self",
".",
"file_opener",
".",
"open_this",
"(",
"file_name",
",",
"\"r\"",
")",
"as",
"infile",
":",
"for",
"line",
"in",
"infile",
":",
"leading_white",
"=",
"self",
".",
"leading_whitespace",
"(",
"line",
")",
"version",
",",
"version_token",
"=",
"dunder_version",
".",
"find_in_line",
"(",
"line",
")",
"if",
"version",
":",
"simplified_line",
"=",
"dunder_version",
".",
"simplify_line",
"(",
"line",
",",
"keep_comma",
"=",
"True",
")",
"if",
"simplified_line",
".",
"strip",
"(",
"\" \\t\\n\"",
")",
".",
"endswith",
"(",
"\",\"",
")",
":",
"comma",
"=",
"\",\"",
"else",
":",
"comma",
"=",
"\"\"",
"if",
"simplified_line",
".",
"strip",
"(",
"\" \\t\\n\"",
")",
".",
"startswith",
"(",
"\",\"",
")",
":",
"start_comma",
"=",
"\",\"",
"else",
":",
"start_comma",
"=",
"\"\"",
"to_write",
".",
"append",
"(",
"'{0}{1}{2} = \"{3}\"{4}{5}\\n'",
".",
"format",
"(",
"start_comma",
",",
"leading_white",
",",
"version_token",
",",
"unicode",
"(",
"self",
".",
"version_to_write",
"(",
")",
")",
",",
"comma",
",",
"self",
".",
"signature",
",",
")",
")",
"else",
":",
"to_write",
".",
"append",
"(",
"line",
")",
"check",
"(",
"self",
".",
"file_opener",
".",
"open_this",
"(",
"file_name",
",",
"\"r\"",
")",
".",
"read",
"(",
")",
",",
"\"\"",
".",
"join",
"(",
"to_write",
")",
")",
"with",
"open",
"(",
"file_name",
",",
"\"w\"",
")",
"as",
"outfile",
":",
"outfile",
".",
"writelines",
"(",
"to_write",
")",
"changed",
"+=",
"1",
"return",
"changed"
] |
Updates version of central package
|
[
"Updates",
"version",
"of",
"central",
"package"
] |
963656a0a47b7162780a5f6c8f4b8bbbebc148f5
|
https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/jiggle_class.py#L176-L227
|
245,444
|
matthewdeanmartin/jiggle_version
|
jiggle_version/jiggle_class.py
|
JiggleVersion.jiggle_config_file
|
def jiggle_config_file(self): # type: () ->int
"""
Update ini, cfg, conf
"""
changed = 0
# setup.py related. setup.py itself should read __init__.py or __version__.py
other_files = ["setup.cfg"]
for file_name in other_files:
filepath = os.path.join(self.SRC, file_name)
# only create setup.cfg if we have setup.py
if (
self.create_configs
and not os.path.isfile(filepath)
and os.path.isfile("setup.py")
):
logger.info("Creating " + unicode(filepath))
self.file_maker.create_setup_cfg(filepath)
if os.path.isfile(filepath):
config = configparser.ConfigParser()
config.read(filepath)
try:
version = config["metadata"]["version"]
except KeyError:
version = ""
if version:
with io.open(filepath, "w") as configfile: # save
config["metadata"]["version"] = unicode(self.version_to_write())
config.write(configfile)
changed += 1
return changed
|
python
|
def jiggle_config_file(self): # type: () ->int
"""
Update ini, cfg, conf
"""
changed = 0
# setup.py related. setup.py itself should read __init__.py or __version__.py
other_files = ["setup.cfg"]
for file_name in other_files:
filepath = os.path.join(self.SRC, file_name)
# only create setup.cfg if we have setup.py
if (
self.create_configs
and not os.path.isfile(filepath)
and os.path.isfile("setup.py")
):
logger.info("Creating " + unicode(filepath))
self.file_maker.create_setup_cfg(filepath)
if os.path.isfile(filepath):
config = configparser.ConfigParser()
config.read(filepath)
try:
version = config["metadata"]["version"]
except KeyError:
version = ""
if version:
with io.open(filepath, "w") as configfile: # save
config["metadata"]["version"] = unicode(self.version_to_write())
config.write(configfile)
changed += 1
return changed
|
[
"def",
"jiggle_config_file",
"(",
"self",
")",
":",
"# type: () ->int",
"changed",
"=",
"0",
"# setup.py related. setup.py itself should read __init__.py or __version__.py",
"other_files",
"=",
"[",
"\"setup.cfg\"",
"]",
"for",
"file_name",
"in",
"other_files",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"SRC",
",",
"file_name",
")",
"# only create setup.cfg if we have setup.py",
"if",
"(",
"self",
".",
"create_configs",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"\"setup.py\"",
")",
")",
":",
"logger",
".",
"info",
"(",
"\"Creating \"",
"+",
"unicode",
"(",
"filepath",
")",
")",
"self",
".",
"file_maker",
".",
"create_setup_cfg",
"(",
"filepath",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
":",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"filepath",
")",
"try",
":",
"version",
"=",
"config",
"[",
"\"metadata\"",
"]",
"[",
"\"version\"",
"]",
"except",
"KeyError",
":",
"version",
"=",
"\"\"",
"if",
"version",
":",
"with",
"io",
".",
"open",
"(",
"filepath",
",",
"\"w\"",
")",
"as",
"configfile",
":",
"# save",
"config",
"[",
"\"metadata\"",
"]",
"[",
"\"version\"",
"]",
"=",
"unicode",
"(",
"self",
".",
"version_to_write",
"(",
")",
")",
"config",
".",
"write",
"(",
"configfile",
")",
"changed",
"+=",
"1",
"return",
"changed"
] |
Update ini, cfg, conf
|
[
"Update",
"ini",
"cfg",
"conf"
] |
963656a0a47b7162780a5f6c8f4b8bbbebc148f5
|
https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/jiggle_class.py#L356-L389
|
245,445
|
Nixiware/viper
|
nx/viper/application.py
|
Application._getConfiguration
|
def _getConfiguration(self):
"""
Load application configuration files.
:return: <dict>
"""
configDirectoryPath = os.path.join("application", "config")
config = Config(configDirectoryPath)
configData = config.getData()
# setting application parameters
reactor.suggestThreadPoolSize(
int(configData["performance"]["threadPoolSize"])
)
return configData
|
python
|
def _getConfiguration(self):
"""
Load application configuration files.
:return: <dict>
"""
configDirectoryPath = os.path.join("application", "config")
config = Config(configDirectoryPath)
configData = config.getData()
# setting application parameters
reactor.suggestThreadPoolSize(
int(configData["performance"]["threadPoolSize"])
)
return configData
|
[
"def",
"_getConfiguration",
"(",
"self",
")",
":",
"configDirectoryPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"application\"",
",",
"\"config\"",
")",
"config",
"=",
"Config",
"(",
"configDirectoryPath",
")",
"configData",
"=",
"config",
".",
"getData",
"(",
")",
"# setting application parameters",
"reactor",
".",
"suggestThreadPoolSize",
"(",
"int",
"(",
"configData",
"[",
"\"performance\"",
"]",
"[",
"\"threadPoolSize\"",
"]",
")",
")",
"return",
"configData"
] |
Load application configuration files.
:return: <dict>
|
[
"Load",
"application",
"configuration",
"files",
"."
] |
fbe6057facd8d46103e9955880dfd99e63b7acb3
|
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L42-L57
|
245,446
|
Nixiware/viper
|
nx/viper/application.py
|
Application._getInterfaces
|
def _getInterfaces(self):
"""
Load application communication interfaces.
:return: <dict>
"""
interfaces = {}
interfacesPath = os.path.join("application", "interface")
interfaceList = os.listdir(interfacesPath)
for file in interfaceList:
interfaceDirectoryPath = os.path.join(interfacesPath, file)
if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."):
continue
interfaceName = ntpath.basename(interfaceDirectoryPath)
interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py"
if not os.path.isfile(interfacePath):
continue
# importing interface
interfaceSpec = importlib.util.spec_from_file_location(
interfaceName,
interfacePath
)
interface = importlib.util.module_from_spec(interfaceSpec)
interfaceSpec.loader.exec_module(interface)
# checking if there is an interface in the file
if hasattr(interface, "Service"):
# initializing interface
interfaceInstance = interface.Service(self)
interfaces[interfaceName] = interfaceInstance
return interfaces
|
python
|
def _getInterfaces(self):
"""
Load application communication interfaces.
:return: <dict>
"""
interfaces = {}
interfacesPath = os.path.join("application", "interface")
interfaceList = os.listdir(interfacesPath)
for file in interfaceList:
interfaceDirectoryPath = os.path.join(interfacesPath, file)
if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."):
continue
interfaceName = ntpath.basename(interfaceDirectoryPath)
interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py"
if not os.path.isfile(interfacePath):
continue
# importing interface
interfaceSpec = importlib.util.spec_from_file_location(
interfaceName,
interfacePath
)
interface = importlib.util.module_from_spec(interfaceSpec)
interfaceSpec.loader.exec_module(interface)
# checking if there is an interface in the file
if hasattr(interface, "Service"):
# initializing interface
interfaceInstance = interface.Service(self)
interfaces[interfaceName] = interfaceInstance
return interfaces
|
[
"def",
"_getInterfaces",
"(",
"self",
")",
":",
"interfaces",
"=",
"{",
"}",
"interfacesPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"application\"",
",",
"\"interface\"",
")",
"interfaceList",
"=",
"os",
".",
"listdir",
"(",
"interfacesPath",
")",
"for",
"file",
"in",
"interfaceList",
":",
"interfaceDirectoryPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"interfacesPath",
",",
"file",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"interfaceDirectoryPath",
")",
"or",
"file",
".",
"startswith",
"(",
"\"__\"",
")",
"or",
"file",
".",
"startswith",
"(",
"\".\"",
")",
":",
"continue",
"interfaceName",
"=",
"ntpath",
".",
"basename",
"(",
"interfaceDirectoryPath",
")",
"interfacePath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"interfaceDirectoryPath",
",",
"interfaceName",
")",
"+",
"\".py\"",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"interfacePath",
")",
":",
"continue",
"# importing interface",
"interfaceSpec",
"=",
"importlib",
".",
"util",
".",
"spec_from_file_location",
"(",
"interfaceName",
",",
"interfacePath",
")",
"interface",
"=",
"importlib",
".",
"util",
".",
"module_from_spec",
"(",
"interfaceSpec",
")",
"interfaceSpec",
".",
"loader",
".",
"exec_module",
"(",
"interface",
")",
"# checking if there is an interface in the file",
"if",
"hasattr",
"(",
"interface",
",",
"\"Service\"",
")",
":",
"# initializing interface",
"interfaceInstance",
"=",
"interface",
".",
"Service",
"(",
"self",
")",
"interfaces",
"[",
"interfaceName",
"]",
"=",
"interfaceInstance",
"return",
"interfaces"
] |
Load application communication interfaces.
:return: <dict>
|
[
"Load",
"application",
"communication",
"interfaces",
"."
] |
fbe6057facd8d46103e9955880dfd99e63b7acb3
|
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L62-L98
|
245,447
|
Nixiware/viper
|
nx/viper/application.py
|
Application._getModules
|
def _getModules(self):
"""
Import and load application modules.
:return: <dict>
"""
modules = {}
modulesPath = os.path.join("application", "module")
moduleList = os.listdir(modulesPath)
for moduleName in moduleList:
modulePath = os.path.join(modulesPath, moduleName, "module.py")
if not os.path.isfile(modulePath):
continue
# importing module
moduleSpec = importlib.util.spec_from_file_location(
moduleName,
modulePath
)
module = importlib.util.module_from_spec(moduleSpec)
moduleSpec.loader.exec_module(module)
# initializing module
moduleInstance = module.Module(self)
modules[moduleName] = moduleInstance
return modules
|
python
|
def _getModules(self):
"""
Import and load application modules.
:return: <dict>
"""
modules = {}
modulesPath = os.path.join("application", "module")
moduleList = os.listdir(modulesPath)
for moduleName in moduleList:
modulePath = os.path.join(modulesPath, moduleName, "module.py")
if not os.path.isfile(modulePath):
continue
# importing module
moduleSpec = importlib.util.spec_from_file_location(
moduleName,
modulePath
)
module = importlib.util.module_from_spec(moduleSpec)
moduleSpec.loader.exec_module(module)
# initializing module
moduleInstance = module.Module(self)
modules[moduleName] = moduleInstance
return modules
|
[
"def",
"_getModules",
"(",
"self",
")",
":",
"modules",
"=",
"{",
"}",
"modulesPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"application\"",
",",
"\"module\"",
")",
"moduleList",
"=",
"os",
".",
"listdir",
"(",
"modulesPath",
")",
"for",
"moduleName",
"in",
"moduleList",
":",
"modulePath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"modulesPath",
",",
"moduleName",
",",
"\"module.py\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"modulePath",
")",
":",
"continue",
"# importing module",
"moduleSpec",
"=",
"importlib",
".",
"util",
".",
"spec_from_file_location",
"(",
"moduleName",
",",
"modulePath",
")",
"module",
"=",
"importlib",
".",
"util",
".",
"module_from_spec",
"(",
"moduleSpec",
")",
"moduleSpec",
".",
"loader",
".",
"exec_module",
"(",
"module",
")",
"# initializing module",
"moduleInstance",
"=",
"module",
".",
"Module",
"(",
"self",
")",
"modules",
"[",
"moduleName",
"]",
"=",
"moduleInstance",
"return",
"modules"
] |
Import and load application modules.
:return: <dict>
|
[
"Import",
"and",
"load",
"application",
"modules",
"."
] |
fbe6057facd8d46103e9955880dfd99e63b7acb3
|
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L111-L138
|
245,448
|
Nixiware/viper
|
nx/viper/application.py
|
Application.addModel
|
def addModel(self, moduleName, modelName, model):
"""
Add a model instance to the application model pool.
:param moduleName: <str> module name in which the model is located
:param modelName: <str> model name
:param model: <object> model instance
:return: <void>
"""
modelIdentifier = "{}.{}".format(moduleName, modelName)
if modelIdentifier not in self._models:
self._models[modelIdentifier] = model
else:
message = "Application - addModel() - " \
"A model with the identifier {} already exists." \
.format(modelIdentifier)
raise Exception(message)
|
python
|
def addModel(self, moduleName, modelName, model):
"""
Add a model instance to the application model pool.
:param moduleName: <str> module name in which the model is located
:param modelName: <str> model name
:param model: <object> model instance
:return: <void>
"""
modelIdentifier = "{}.{}".format(moduleName, modelName)
if modelIdentifier not in self._models:
self._models[modelIdentifier] = model
else:
message = "Application - addModel() - " \
"A model with the identifier {} already exists." \
.format(modelIdentifier)
raise Exception(message)
|
[
"def",
"addModel",
"(",
"self",
",",
"moduleName",
",",
"modelName",
",",
"model",
")",
":",
"modelIdentifier",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"moduleName",
",",
"modelName",
")",
"if",
"modelIdentifier",
"not",
"in",
"self",
".",
"_models",
":",
"self",
".",
"_models",
"[",
"modelIdentifier",
"]",
"=",
"model",
"else",
":",
"message",
"=",
"\"Application - addModel() - \"",
"\"A model with the identifier {} already exists.\"",
".",
"format",
"(",
"modelIdentifier",
")",
"raise",
"Exception",
"(",
"message",
")"
] |
Add a model instance to the application model pool.
:param moduleName: <str> module name in which the model is located
:param modelName: <str> model name
:param model: <object> model instance
:return: <void>
|
[
"Add",
"a",
"model",
"instance",
"to",
"the",
"application",
"model",
"pool",
"."
] |
fbe6057facd8d46103e9955880dfd99e63b7acb3
|
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L155-L171
|
245,449
|
Nixiware/viper
|
nx/viper/application.py
|
Application.getModel
|
def getModel(self, modelIdentifier):
"""
Return the requested model.
:param modelIdentifier: <str> model identifier
:return: <object> model instance
"""
if modelIdentifier in self._models:
return self._models[modelIdentifier]
else:
message = "Application - getModel() - " \
"Model with identifier {} does not exist." \
.format(modelIdentifier)
raise Exception(message)
|
python
|
def getModel(self, modelIdentifier):
"""
Return the requested model.
:param modelIdentifier: <str> model identifier
:return: <object> model instance
"""
if modelIdentifier in self._models:
return self._models[modelIdentifier]
else:
message = "Application - getModel() - " \
"Model with identifier {} does not exist." \
.format(modelIdentifier)
raise Exception(message)
|
[
"def",
"getModel",
"(",
"self",
",",
"modelIdentifier",
")",
":",
"if",
"modelIdentifier",
"in",
"self",
".",
"_models",
":",
"return",
"self",
".",
"_models",
"[",
"modelIdentifier",
"]",
"else",
":",
"message",
"=",
"\"Application - getModel() - \"",
"\"Model with identifier {} does not exist.\"",
".",
"format",
"(",
"modelIdentifier",
")",
"raise",
"Exception",
"(",
"message",
")"
] |
Return the requested model.
:param modelIdentifier: <str> model identifier
:return: <object> model instance
|
[
"Return",
"the",
"requested",
"model",
"."
] |
fbe6057facd8d46103e9955880dfd99e63b7acb3
|
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L173-L186
|
245,450
|
Nixiware/viper
|
nx/viper/application.py
|
Application._loadViperServices
|
def _loadViperServices(self):
"""
Load application bundled services.
:return: <void>
"""
servicesPath = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"service"
)
for serviceFile in os.listdir(servicesPath):
if serviceFile.startswith("__") or serviceFile.startswith("."):
continue
serviceName = serviceFile.replace(".py", "")
servicePath = os.path.join(
servicesPath, serviceFile
)
if not os.path.isfile(servicePath):
continue
# importing service
serviceSpec = importlib.util.spec_from_file_location(
serviceName,
servicePath
)
service = importlib.util.module_from_spec(serviceSpec)
serviceSpec.loader.exec_module(service)
# initializing service
serviceInstance = service.Service(self)
self.addService("viper", serviceName, serviceInstance)
|
python
|
def _loadViperServices(self):
"""
Load application bundled services.
:return: <void>
"""
servicesPath = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"service"
)
for serviceFile in os.listdir(servicesPath):
if serviceFile.startswith("__") or serviceFile.startswith("."):
continue
serviceName = serviceFile.replace(".py", "")
servicePath = os.path.join(
servicesPath, serviceFile
)
if not os.path.isfile(servicePath):
continue
# importing service
serviceSpec = importlib.util.spec_from_file_location(
serviceName,
servicePath
)
service = importlib.util.module_from_spec(serviceSpec)
serviceSpec.loader.exec_module(service)
# initializing service
serviceInstance = service.Service(self)
self.addService("viper", serviceName, serviceInstance)
|
[
"def",
"_loadViperServices",
"(",
"self",
")",
":",
"servicesPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
",",
"\"service\"",
")",
"for",
"serviceFile",
"in",
"os",
".",
"listdir",
"(",
"servicesPath",
")",
":",
"if",
"serviceFile",
".",
"startswith",
"(",
"\"__\"",
")",
"or",
"serviceFile",
".",
"startswith",
"(",
"\".\"",
")",
":",
"continue",
"serviceName",
"=",
"serviceFile",
".",
"replace",
"(",
"\".py\"",
",",
"\"\"",
")",
"servicePath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"servicesPath",
",",
"serviceFile",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"servicePath",
")",
":",
"continue",
"# importing service",
"serviceSpec",
"=",
"importlib",
".",
"util",
".",
"spec_from_file_location",
"(",
"serviceName",
",",
"servicePath",
")",
"service",
"=",
"importlib",
".",
"util",
".",
"module_from_spec",
"(",
"serviceSpec",
")",
"serviceSpec",
".",
"loader",
".",
"exec_module",
"(",
"service",
")",
"# initializing service",
"serviceInstance",
"=",
"service",
".",
"Service",
"(",
"self",
")",
"self",
".",
"addService",
"(",
"\"viper\"",
",",
"serviceName",
",",
"serviceInstance",
")"
] |
Load application bundled services.
:return: <void>
|
[
"Load",
"application",
"bundled",
"services",
"."
] |
fbe6057facd8d46103e9955880dfd99e63b7acb3
|
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L191-L223
|
245,451
|
Nixiware/viper
|
nx/viper/application.py
|
Application.addService
|
def addService(self, moduleName, serviceName, service):
"""
Add a service instance to the application service pool.
:param moduleName: <str> module name in which the service is located
:param serviceName: <str> service name
:param service: <object> service instance
:return: <void>
"""
serviceIdentifier = "{}.{}".format(moduleName, serviceName)
if serviceIdentifier not in self._services:
self._services[serviceIdentifier] = service
else:
message = "Application - addService() - " \
"A service with the identifier {} already exists." \
.format(serviceIdentifier)
raise Exception(message)
|
python
|
def addService(self, moduleName, serviceName, service):
"""
Add a service instance to the application service pool.
:param moduleName: <str> module name in which the service is located
:param serviceName: <str> service name
:param service: <object> service instance
:return: <void>
"""
serviceIdentifier = "{}.{}".format(moduleName, serviceName)
if serviceIdentifier not in self._services:
self._services[serviceIdentifier] = service
else:
message = "Application - addService() - " \
"A service with the identifier {} already exists." \
.format(serviceIdentifier)
raise Exception(message)
|
[
"def",
"addService",
"(",
"self",
",",
"moduleName",
",",
"serviceName",
",",
"service",
")",
":",
"serviceIdentifier",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"moduleName",
",",
"serviceName",
")",
"if",
"serviceIdentifier",
"not",
"in",
"self",
".",
"_services",
":",
"self",
".",
"_services",
"[",
"serviceIdentifier",
"]",
"=",
"service",
"else",
":",
"message",
"=",
"\"Application - addService() - \"",
"\"A service with the identifier {} already exists.\"",
".",
"format",
"(",
"serviceIdentifier",
")",
"raise",
"Exception",
"(",
"message",
")"
] |
Add a service instance to the application service pool.
:param moduleName: <str> module name in which the service is located
:param serviceName: <str> service name
:param service: <object> service instance
:return: <void>
|
[
"Add",
"a",
"service",
"instance",
"to",
"the",
"application",
"service",
"pool",
"."
] |
fbe6057facd8d46103e9955880dfd99e63b7acb3
|
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L225-L241
|
245,452
|
Nixiware/viper
|
nx/viper/application.py
|
Application.getService
|
def getService(self, serviceIdentifier):
"""
Return the requested service instance.
:param serviceIdentifier: <str> service identifier
:return: <object> service instance
"""
if serviceIdentifier in self._services:
return self._services[serviceIdentifier]
else:
message = "Application - getService() - " \
"Service with identifier {} does not exist." \
.format(serviceIdentifier)
raise Exception(message)
|
python
|
def getService(self, serviceIdentifier):
"""
Return the requested service instance.
:param serviceIdentifier: <str> service identifier
:return: <object> service instance
"""
if serviceIdentifier in self._services:
return self._services[serviceIdentifier]
else:
message = "Application - getService() - " \
"Service with identifier {} does not exist." \
.format(serviceIdentifier)
raise Exception(message)
|
[
"def",
"getService",
"(",
"self",
",",
"serviceIdentifier",
")",
":",
"if",
"serviceIdentifier",
"in",
"self",
".",
"_services",
":",
"return",
"self",
".",
"_services",
"[",
"serviceIdentifier",
"]",
"else",
":",
"message",
"=",
"\"Application - getService() - \"",
"\"Service with identifier {} does not exist.\"",
".",
"format",
"(",
"serviceIdentifier",
")",
"raise",
"Exception",
"(",
"message",
")"
] |
Return the requested service instance.
:param serviceIdentifier: <str> service identifier
:return: <object> service instance
|
[
"Return",
"the",
"requested",
"service",
"instance",
"."
] |
fbe6057facd8d46103e9955880dfd99e63b7acb3
|
https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/application.py#L243-L256
|
245,453
|
neumark/microcli
|
example.py
|
Calculator.add
|
def add(self, *number):
"""Adds all parameters interpreted as integers"""
return self._format_result(sum(
# positional arguments are always strings
[int(n) for n in number]))
|
python
|
def add(self, *number):
"""Adds all parameters interpreted as integers"""
return self._format_result(sum(
# positional arguments are always strings
[int(n) for n in number]))
|
[
"def",
"add",
"(",
"self",
",",
"*",
"number",
")",
":",
"return",
"self",
".",
"_format_result",
"(",
"sum",
"(",
"# positional arguments are always strings",
"[",
"int",
"(",
"n",
")",
"for",
"n",
"in",
"number",
"]",
")",
")"
] |
Adds all parameters interpreted as integers
|
[
"Adds",
"all",
"parameters",
"interpreted",
"as",
"integers"
] |
fa31a35a95f63593ca12d246a5a84e2dff522dd6
|
https://github.com/neumark/microcli/blob/fa31a35a95f63593ca12d246a5a84e2dff522dd6/example.py#L27-L31
|
245,454
|
neumark/microcli
|
example.py
|
Calculator.subtract
|
def subtract(self, number1, number2):
"""Subtracts number2 from number1"""
return self._format_result(int(number1) - int(number2))
|
python
|
def subtract(self, number1, number2):
"""Subtracts number2 from number1"""
return self._format_result(int(number1) - int(number2))
|
[
"def",
"subtract",
"(",
"self",
",",
"number1",
",",
"number2",
")",
":",
"return",
"self",
".",
"_format_result",
"(",
"int",
"(",
"number1",
")",
"-",
"int",
"(",
"number2",
")",
")"
] |
Subtracts number2 from number1
|
[
"Subtracts",
"number2",
"from",
"number1"
] |
fa31a35a95f63593ca12d246a5a84e2dff522dd6
|
https://github.com/neumark/microcli/blob/fa31a35a95f63593ca12d246a5a84e2dff522dd6/example.py#L34-L36
|
245,455
|
johnnoone/facts
|
facts/logical.py
|
Logical.items
|
async def items(self):
"""Expose all grafts.
"""
accumulator = Accumulator()
for graft in load_grafts():
accumulator.spawn(graft())
response = await accumulator.join()
return response.items()
|
python
|
async def items(self):
"""Expose all grafts.
"""
accumulator = Accumulator()
for graft in load_grafts():
accumulator.spawn(graft())
response = await accumulator.join()
return response.items()
|
[
"async",
"def",
"items",
"(",
"self",
")",
":",
"accumulator",
"=",
"Accumulator",
"(",
")",
"for",
"graft",
"in",
"load_grafts",
"(",
")",
":",
"accumulator",
".",
"spawn",
"(",
"graft",
"(",
")",
")",
"response",
"=",
"await",
"accumulator",
".",
"join",
"(",
")",
"return",
"response",
".",
"items",
"(",
")"
] |
Expose all grafts.
|
[
"Expose",
"all",
"grafts",
"."
] |
82d38a46c15d9c01200445526f4c0d1825fc1e51
|
https://github.com/johnnoone/facts/blob/82d38a46c15d9c01200445526f4c0d1825fc1e51/facts/logical.py#L12-L20
|
245,456
|
edeposit/edeposit.amqp.ftp
|
src/edeposit/amqp/ftp/settings.py
|
conf_merger
|
def conf_merger(user_dict, variable):
"""
Merge global configuration with user's personal configuration.
Global configuration has always higher priority.
"""
if variable not in globals().keys():
raise NameError("Unknown variable '%s'." % variable)
if variable not in user_dict:
return globals()[variable]
return globals()[variable] and user_dict[variable]
|
python
|
def conf_merger(user_dict, variable):
"""
Merge global configuration with user's personal configuration.
Global configuration has always higher priority.
"""
if variable not in globals().keys():
raise NameError("Unknown variable '%s'." % variable)
if variable not in user_dict:
return globals()[variable]
return globals()[variable] and user_dict[variable]
|
[
"def",
"conf_merger",
"(",
"user_dict",
",",
"variable",
")",
":",
"if",
"variable",
"not",
"in",
"globals",
"(",
")",
".",
"keys",
"(",
")",
":",
"raise",
"NameError",
"(",
"\"Unknown variable '%s'.\"",
"%",
"variable",
")",
"if",
"variable",
"not",
"in",
"user_dict",
":",
"return",
"globals",
"(",
")",
"[",
"variable",
"]",
"return",
"globals",
"(",
")",
"[",
"variable",
"]",
"and",
"user_dict",
"[",
"variable",
"]"
] |
Merge global configuration with user's personal configuration.
Global configuration has always higher priority.
|
[
"Merge",
"global",
"configuration",
"with",
"user",
"s",
"personal",
"configuration",
"."
] |
fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71
|
https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/settings.py#L121-L133
|
245,457
|
toastdriven/alligator
|
alligator/backends/beanstalk_backend.py
|
Client.len
|
def len(self, queue_name):
"""
Returns the length of the queue.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
:returns: The length of the queue
:rtype: integer
"""
try:
stats = self.conn.stats_tube(queue_name)
except beanstalkc.CommandFailed as err:
if err[1] == 'NOT_FOUND':
return 0
raise
return stats.get('current-jobs-ready', 0)
|
python
|
def len(self, queue_name):
"""
Returns the length of the queue.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
:returns: The length of the queue
:rtype: integer
"""
try:
stats = self.conn.stats_tube(queue_name)
except beanstalkc.CommandFailed as err:
if err[1] == 'NOT_FOUND':
return 0
raise
return stats.get('current-jobs-ready', 0)
|
[
"def",
"len",
"(",
"self",
",",
"queue_name",
")",
":",
"try",
":",
"stats",
"=",
"self",
".",
"conn",
".",
"stats_tube",
"(",
"queue_name",
")",
"except",
"beanstalkc",
".",
"CommandFailed",
"as",
"err",
":",
"if",
"err",
"[",
"1",
"]",
"==",
"'NOT_FOUND'",
":",
"return",
"0",
"raise",
"return",
"stats",
".",
"get",
"(",
"'current-jobs-ready'",
",",
"0",
")"
] |
Returns the length of the queue.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
:returns: The length of the queue
:rtype: integer
|
[
"Returns",
"the",
"length",
"of",
"the",
"queue",
"."
] |
f18bcb35b350fc6b0886393f5246d69c892b36c7
|
https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/backends/beanstalk_backend.py#L34-L53
|
245,458
|
dossier/dossier.models
|
dossier/models/pairwise.py
|
add_facets
|
def add_facets(engine_result, facet_features=None):
'''Adds facets to search results.
Construct a new result payload with `facets` added as a new
top-level property that carries a mapping from unicode strings to
lists of content_ids. The `facet_features` lists the names of
:class:`~dossier.fc.StringCounter` features in each result
:class:`~dossier.fc.FeatureCollection` to harvest phrases for the
facets list. If not specified, `facet_features` defaults to
`bowNP_sip`.
The remainder of the facet logic is handled in the UI.
'''
if facet_features is None:
facet_features = ['bowNP_sip']
phrases = collections.defaultdict(list)
for r in engine_result['results']:
cid = r[0]
fc = r[1]
for fname in facet_features:
for phrase in fc.get(u'bowNP_sip', []):
phrases[phrase].append(cid)
return dict(engine_result, **{'facets': dict(phrases)})
|
python
|
def add_facets(engine_result, facet_features=None):
'''Adds facets to search results.
Construct a new result payload with `facets` added as a new
top-level property that carries a mapping from unicode strings to
lists of content_ids. The `facet_features` lists the names of
:class:`~dossier.fc.StringCounter` features in each result
:class:`~dossier.fc.FeatureCollection` to harvest phrases for the
facets list. If not specified, `facet_features` defaults to
`bowNP_sip`.
The remainder of the facet logic is handled in the UI.
'''
if facet_features is None:
facet_features = ['bowNP_sip']
phrases = collections.defaultdict(list)
for r in engine_result['results']:
cid = r[0]
fc = r[1]
for fname in facet_features:
for phrase in fc.get(u'bowNP_sip', []):
phrases[phrase].append(cid)
return dict(engine_result, **{'facets': dict(phrases)})
|
[
"def",
"add_facets",
"(",
"engine_result",
",",
"facet_features",
"=",
"None",
")",
":",
"if",
"facet_features",
"is",
"None",
":",
"facet_features",
"=",
"[",
"'bowNP_sip'",
"]",
"phrases",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"r",
"in",
"engine_result",
"[",
"'results'",
"]",
":",
"cid",
"=",
"r",
"[",
"0",
"]",
"fc",
"=",
"r",
"[",
"1",
"]",
"for",
"fname",
"in",
"facet_features",
":",
"for",
"phrase",
"in",
"fc",
".",
"get",
"(",
"u'bowNP_sip'",
",",
"[",
"]",
")",
":",
"phrases",
"[",
"phrase",
"]",
".",
"append",
"(",
"cid",
")",
"return",
"dict",
"(",
"engine_result",
",",
"*",
"*",
"{",
"'facets'",
":",
"dict",
"(",
"phrases",
")",
"}",
")"
] |
Adds facets to search results.
Construct a new result payload with `facets` added as a new
top-level property that carries a mapping from unicode strings to
lists of content_ids. The `facet_features` lists the names of
:class:`~dossier.fc.StringCounter` features in each result
:class:`~dossier.fc.FeatureCollection` to harvest phrases for the
facets list. If not specified, `facet_features` defaults to
`bowNP_sip`.
The remainder of the facet logic is handled in the UI.
|
[
"Adds",
"facets",
"to",
"search",
"results",
"."
] |
c9e282f690eab72963926329efe1600709e48b13
|
https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/pairwise.py#L98-L120
|
245,459
|
dossier/dossier.models
|
dossier/models/pairwise.py
|
vectorizable_features
|
def vectorizable_features(fcs):
'''Discovers the ordered set of vectorizable features in ``fcs``.
Returns a list of feature names, sorted lexicographically.
Feature names are only included if the corresponding
features are vectorizable (i.e., they are an instance of
:class:`collections.Mapping`).
'''
is_mapping = lambda obj: isinstance(obj, collections.Mapping)
return sorted(set([name for fc in fcs for name in fc if is_mapping(fc[name])]))
|
python
|
def vectorizable_features(fcs):
'''Discovers the ordered set of vectorizable features in ``fcs``.
Returns a list of feature names, sorted lexicographically.
Feature names are only included if the corresponding
features are vectorizable (i.e., they are an instance of
:class:`collections.Mapping`).
'''
is_mapping = lambda obj: isinstance(obj, collections.Mapping)
return sorted(set([name for fc in fcs for name in fc if is_mapping(fc[name])]))
|
[
"def",
"vectorizable_features",
"(",
"fcs",
")",
":",
"is_mapping",
"=",
"lambda",
"obj",
":",
"isinstance",
"(",
"obj",
",",
"collections",
".",
"Mapping",
")",
"return",
"sorted",
"(",
"set",
"(",
"[",
"name",
"for",
"fc",
"in",
"fcs",
"for",
"name",
"in",
"fc",
"if",
"is_mapping",
"(",
"fc",
"[",
"name",
"]",
")",
"]",
")",
")"
] |
Discovers the ordered set of vectorizable features in ``fcs``.
Returns a list of feature names, sorted lexicographically.
Feature names are only included if the corresponding
features are vectorizable (i.e., they are an instance of
:class:`collections.Mapping`).
|
[
"Discovers",
"the",
"ordered",
"set",
"of",
"vectorizable",
"features",
"in",
"fcs",
"."
] |
c9e282f690eab72963926329efe1600709e48b13
|
https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/pairwise.py#L501-L510
|
245,460
|
dossier/dossier.models
|
dossier/models/pairwise.py
|
dissimilarities
|
def dissimilarities(feature_names, fcs):
'''Computes the pairwise dissimilarity matrices.
This returns a dictionary mapping each name in ``feature_names``
to a pairwise dissimilarities matrix. The dissimilaritiy scores
correspond to ``1 - kernel`` between each feature of each
pair of feature collections in ``fcs``.
(The kernel used is currently fixed to ``cosine`` distance.)
'''
dis = {}
for count, name in enumerate(feature_names, 1):
logger.info('computing pairwise dissimilarity matrix '
'for %d of %d features (current feature: %s)',
count, len(feature_names), name)
# opportunity to use joblib is buried down inside call to
# pairwise_distances...
# And it's fixed to `n_jobs=1` because running multiprocessing
# inside py.test causes weird problems. It also doesn't seem like a
# good idea to do it inside a web server either. ---AG
dis[name] = 1 - pairwise_distances(
dict_vector().fit_transform([get_feat(fc, name) for fc in fcs]),
metric='cosine', n_jobs=1)
return dis
|
python
|
def dissimilarities(feature_names, fcs):
'''Computes the pairwise dissimilarity matrices.
This returns a dictionary mapping each name in ``feature_names``
to a pairwise dissimilarities matrix. The dissimilaritiy scores
correspond to ``1 - kernel`` between each feature of each
pair of feature collections in ``fcs``.
(The kernel used is currently fixed to ``cosine`` distance.)
'''
dis = {}
for count, name in enumerate(feature_names, 1):
logger.info('computing pairwise dissimilarity matrix '
'for %d of %d features (current feature: %s)',
count, len(feature_names), name)
# opportunity to use joblib is buried down inside call to
# pairwise_distances...
# And it's fixed to `n_jobs=1` because running multiprocessing
# inside py.test causes weird problems. It also doesn't seem like a
# good idea to do it inside a web server either. ---AG
dis[name] = 1 - pairwise_distances(
dict_vector().fit_transform([get_feat(fc, name) for fc in fcs]),
metric='cosine', n_jobs=1)
return dis
|
[
"def",
"dissimilarities",
"(",
"feature_names",
",",
"fcs",
")",
":",
"dis",
"=",
"{",
"}",
"for",
"count",
",",
"name",
"in",
"enumerate",
"(",
"feature_names",
",",
"1",
")",
":",
"logger",
".",
"info",
"(",
"'computing pairwise dissimilarity matrix '",
"'for %d of %d features (current feature: %s)'",
",",
"count",
",",
"len",
"(",
"feature_names",
")",
",",
"name",
")",
"# opportunity to use joblib is buried down inside call to",
"# pairwise_distances...",
"# And it's fixed to `n_jobs=1` because running multiprocessing",
"# inside py.test causes weird problems. It also doesn't seem like a",
"# good idea to do it inside a web server either. ---AG",
"dis",
"[",
"name",
"]",
"=",
"1",
"-",
"pairwise_distances",
"(",
"dict_vector",
"(",
")",
".",
"fit_transform",
"(",
"[",
"get_feat",
"(",
"fc",
",",
"name",
")",
"for",
"fc",
"in",
"fcs",
"]",
")",
",",
"metric",
"=",
"'cosine'",
",",
"n_jobs",
"=",
"1",
")",
"return",
"dis"
] |
Computes the pairwise dissimilarity matrices.
This returns a dictionary mapping each name in ``feature_names``
to a pairwise dissimilarities matrix. The dissimilaritiy scores
correspond to ``1 - kernel`` between each feature of each
pair of feature collections in ``fcs``.
(The kernel used is currently fixed to ``cosine`` distance.)
|
[
"Computes",
"the",
"pairwise",
"dissimilarity",
"matrices",
"."
] |
c9e282f690eab72963926329efe1600709e48b13
|
https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/pairwise.py#L513-L536
|
245,461
|
dossier/dossier.models
|
dossier/models/pairwise.py
|
PairwiseFeatureLearner.probabilities
|
def probabilities(self):
'''Trains a model and predicts recommendations.
If the query feature collection could not be found or if there
is insufficient training data, an empty list is returned.
Otherwise, a list of content objects (tuples of content
id and feature collection) and probabilities is returned.
The probability is generated from the model, and reflects
confidence of the model that the corresponding content object
is related to the query based on the ground truth data.
On a large database, random samples are used for training, so
this function is not deterministic.
:rtype: ``list`` of
((``content_id``, :class:`dossier.fc.FeatureCollection`),
probability)
'''
self.query_fc = self.store.get(self.query_content_id)
if self.query_fc is None:
logger.warning('Could not find FC for %s', self.query_content_id)
return []
# Try the canopy query before training, because if the canopy query
# gives us nothing, then there's no point in the additional work.
#
# Possible optimization: If the canopy query yields fewer than N
# results, then can we just return all of them? ---AG
#
# N.B Doing the canopy query first will cause things to be slower
# when there is insufficient training data.
candidates = self.canopy(limit=self.canopy_limit)
if len(candidates) == 0:
logger.info(
'Could not find any candidates in a canopy query by '
'scanning the following indexes: %s',
', '.join(self.store.index_names()))
return []
# Get labels from the database and translate them to the form
# `[{-1, 1}, i, j]` where `i, j` are indices into the list
# `content_objs`, which has type `[(content_id, FeatureCollection)]`.
logger.info('Fetching labels...')
labels = list(self.labels_from_query(limit=self.label_limit))
logger.info('Fetching FCs from labels...')
content_objs = self.content_objs_from_labels(labels)
indexed_labels = labels_to_indexed_coref_values(content_objs, labels)
logger.info('Training...')
model = self.train(content_objs, indexed_labels)
if model is None:
logger.info(
'Could not train model: insufficient training data. '
'(query content id: %s)', self.query_content_id)
raise InsufficientTrainingData
feature_names, classifier, transformer = model
return zip(candidates, self.classify(
feature_names, classifier, transformer, candidates))
|
python
|
def probabilities(self):
'''Trains a model and predicts recommendations.
If the query feature collection could not be found or if there
is insufficient training data, an empty list is returned.
Otherwise, a list of content objects (tuples of content
id and feature collection) and probabilities is returned.
The probability is generated from the model, and reflects
confidence of the model that the corresponding content object
is related to the query based on the ground truth data.
On a large database, random samples are used for training, so
this function is not deterministic.
:rtype: ``list`` of
((``content_id``, :class:`dossier.fc.FeatureCollection`),
probability)
'''
self.query_fc = self.store.get(self.query_content_id)
if self.query_fc is None:
logger.warning('Could not find FC for %s', self.query_content_id)
return []
# Try the canopy query before training, because if the canopy query
# gives us nothing, then there's no point in the additional work.
#
# Possible optimization: If the canopy query yields fewer than N
# results, then can we just return all of them? ---AG
#
# N.B Doing the canopy query first will cause things to be slower
# when there is insufficient training data.
candidates = self.canopy(limit=self.canopy_limit)
if len(candidates) == 0:
logger.info(
'Could not find any candidates in a canopy query by '
'scanning the following indexes: %s',
', '.join(self.store.index_names()))
return []
# Get labels from the database and translate them to the form
# `[{-1, 1}, i, j]` where `i, j` are indices into the list
# `content_objs`, which has type `[(content_id, FeatureCollection)]`.
logger.info('Fetching labels...')
labels = list(self.labels_from_query(limit=self.label_limit))
logger.info('Fetching FCs from labels...')
content_objs = self.content_objs_from_labels(labels)
indexed_labels = labels_to_indexed_coref_values(content_objs, labels)
logger.info('Training...')
model = self.train(content_objs, indexed_labels)
if model is None:
logger.info(
'Could not train model: insufficient training data. '
'(query content id: %s)', self.query_content_id)
raise InsufficientTrainingData
feature_names, classifier, transformer = model
return zip(candidates, self.classify(
feature_names, classifier, transformer, candidates))
|
[
"def",
"probabilities",
"(",
"self",
")",
":",
"self",
".",
"query_fc",
"=",
"self",
".",
"store",
".",
"get",
"(",
"self",
".",
"query_content_id",
")",
"if",
"self",
".",
"query_fc",
"is",
"None",
":",
"logger",
".",
"warning",
"(",
"'Could not find FC for %s'",
",",
"self",
".",
"query_content_id",
")",
"return",
"[",
"]",
"# Try the canopy query before training, because if the canopy query",
"# gives us nothing, then there's no point in the additional work.",
"#",
"# Possible optimization: If the canopy query yields fewer than N",
"# results, then can we just return all of them? ---AG",
"#",
"# N.B Doing the canopy query first will cause things to be slower",
"# when there is insufficient training data.",
"candidates",
"=",
"self",
".",
"canopy",
"(",
"limit",
"=",
"self",
".",
"canopy_limit",
")",
"if",
"len",
"(",
"candidates",
")",
"==",
"0",
":",
"logger",
".",
"info",
"(",
"'Could not find any candidates in a canopy query by '",
"'scanning the following indexes: %s'",
",",
"', '",
".",
"join",
"(",
"self",
".",
"store",
".",
"index_names",
"(",
")",
")",
")",
"return",
"[",
"]",
"# Get labels from the database and translate them to the form",
"# `[{-1, 1}, i, j]` where `i, j` are indices into the list",
"# `content_objs`, which has type `[(content_id, FeatureCollection)]`.",
"logger",
".",
"info",
"(",
"'Fetching labels...'",
")",
"labels",
"=",
"list",
"(",
"self",
".",
"labels_from_query",
"(",
"limit",
"=",
"self",
".",
"label_limit",
")",
")",
"logger",
".",
"info",
"(",
"'Fetching FCs from labels...'",
")",
"content_objs",
"=",
"self",
".",
"content_objs_from_labels",
"(",
"labels",
")",
"indexed_labels",
"=",
"labels_to_indexed_coref_values",
"(",
"content_objs",
",",
"labels",
")",
"logger",
".",
"info",
"(",
"'Training...'",
")",
"model",
"=",
"self",
".",
"train",
"(",
"content_objs",
",",
"indexed_labels",
")",
"if",
"model",
"is",
"None",
":",
"logger",
".",
"info",
"(",
"'Could not train model: insufficient training data. '",
"'(query content id: %s)'",
",",
"self",
".",
"query_content_id",
")",
"raise",
"InsufficientTrainingData",
"feature_names",
",",
"classifier",
",",
"transformer",
"=",
"model",
"return",
"zip",
"(",
"candidates",
",",
"self",
".",
"classify",
"(",
"feature_names",
",",
"classifier",
",",
"transformer",
",",
"candidates",
")",
")"
] |
Trains a model and predicts recommendations.
If the query feature collection could not be found or if there
is insufficient training data, an empty list is returned.
Otherwise, a list of content objects (tuples of content
id and feature collection) and probabilities is returned.
The probability is generated from the model, and reflects
confidence of the model that the corresponding content object
is related to the query based on the ground truth data.
On a large database, random samples are used for training, so
this function is not deterministic.
:rtype: ``list`` of
((``content_id``, :class:`dossier.fc.FeatureCollection`),
probability)
|
[
"Trains",
"a",
"model",
"and",
"predicts",
"recommendations",
"."
] |
c9e282f690eab72963926329efe1600709e48b13
|
https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/pairwise.py#L210-L269
|
245,462
|
dossier/dossier.models
|
dossier/models/pairwise.py
|
PairwiseFeatureLearner.train
|
def train(self, content_objs, idx_labels):
'''Trains and returns a model using sklearn.
If there are new labels to add, they can be added, returns an
sklearn model which can be used for prediction and getting
features.
This method may return ``None`` if there is insufficient
training data to produce a model.
:param labels: Ground truth data.
:type labels: list of ``({-1, 1}, index1, index2)``.
'''
# We have insufficient training data when there is only one or
# fewer classes of labels.
if len(set([lab[0] for lab in idx_labels])) <= 1:
return None
fcs = [fc for _, fc in content_objs]
feature_names = vectorizable_features(fcs)
dis = dissimilarities(feature_names, fcs)
phi_dicts, labels = [], [] # lists are in correspondence
for coref_value, i, j in idx_labels:
# i, j are indices into the list `fcs`
labels.append(coref_value) # either -1 or 1
phi_dict = dict([(name, dis[name][i,j]) for name in feature_names])
phi_dicts.append(phi_dict)
vec = dict_vector()
training_data = vec.fit_transform(phi_dicts)
model = LogisticRegression(class_weight='auto', penalty='l1')
model.fit(training_data, labels)
self.feature_weights = dict([(name, model.coef_[0][i])
for i, name in enumerate(feature_names)])
return feature_names, model, vec
|
python
|
def train(self, content_objs, idx_labels):
'''Trains and returns a model using sklearn.
If there are new labels to add, they can be added, returns an
sklearn model which can be used for prediction and getting
features.
This method may return ``None`` if there is insufficient
training data to produce a model.
:param labels: Ground truth data.
:type labels: list of ``({-1, 1}, index1, index2)``.
'''
# We have insufficient training data when there is only one or
# fewer classes of labels.
if len(set([lab[0] for lab in idx_labels])) <= 1:
return None
fcs = [fc for _, fc in content_objs]
feature_names = vectorizable_features(fcs)
dis = dissimilarities(feature_names, fcs)
phi_dicts, labels = [], [] # lists are in correspondence
for coref_value, i, j in idx_labels:
# i, j are indices into the list `fcs`
labels.append(coref_value) # either -1 or 1
phi_dict = dict([(name, dis[name][i,j]) for name in feature_names])
phi_dicts.append(phi_dict)
vec = dict_vector()
training_data = vec.fit_transform(phi_dicts)
model = LogisticRegression(class_weight='auto', penalty='l1')
model.fit(training_data, labels)
self.feature_weights = dict([(name, model.coef_[0][i])
for i, name in enumerate(feature_names)])
return feature_names, model, vec
|
[
"def",
"train",
"(",
"self",
",",
"content_objs",
",",
"idx_labels",
")",
":",
"# We have insufficient training data when there is only one or",
"# fewer classes of labels.",
"if",
"len",
"(",
"set",
"(",
"[",
"lab",
"[",
"0",
"]",
"for",
"lab",
"in",
"idx_labels",
"]",
")",
")",
"<=",
"1",
":",
"return",
"None",
"fcs",
"=",
"[",
"fc",
"for",
"_",
",",
"fc",
"in",
"content_objs",
"]",
"feature_names",
"=",
"vectorizable_features",
"(",
"fcs",
")",
"dis",
"=",
"dissimilarities",
"(",
"feature_names",
",",
"fcs",
")",
"phi_dicts",
",",
"labels",
"=",
"[",
"]",
",",
"[",
"]",
"# lists are in correspondence",
"for",
"coref_value",
",",
"i",
",",
"j",
"in",
"idx_labels",
":",
"# i, j are indices into the list `fcs`",
"labels",
".",
"append",
"(",
"coref_value",
")",
"# either -1 or 1",
"phi_dict",
"=",
"dict",
"(",
"[",
"(",
"name",
",",
"dis",
"[",
"name",
"]",
"[",
"i",
",",
"j",
"]",
")",
"for",
"name",
"in",
"feature_names",
"]",
")",
"phi_dicts",
".",
"append",
"(",
"phi_dict",
")",
"vec",
"=",
"dict_vector",
"(",
")",
"training_data",
"=",
"vec",
".",
"fit_transform",
"(",
"phi_dicts",
")",
"model",
"=",
"LogisticRegression",
"(",
"class_weight",
"=",
"'auto'",
",",
"penalty",
"=",
"'l1'",
")",
"model",
".",
"fit",
"(",
"training_data",
",",
"labels",
")",
"self",
".",
"feature_weights",
"=",
"dict",
"(",
"[",
"(",
"name",
",",
"model",
".",
"coef_",
"[",
"0",
"]",
"[",
"i",
"]",
")",
"for",
"i",
",",
"name",
"in",
"enumerate",
"(",
"feature_names",
")",
"]",
")",
"return",
"feature_names",
",",
"model",
",",
"vec"
] |
Trains and returns a model using sklearn.
If there are new labels to add, they can be added, returns an
sklearn model which can be used for prediction and getting
features.
This method may return ``None`` if there is insufficient
training data to produce a model.
:param labels: Ground truth data.
:type labels: list of ``({-1, 1}, index1, index2)``.
|
[
"Trains",
"and",
"returns",
"a",
"model",
"using",
"sklearn",
"."
] |
c9e282f690eab72963926329efe1600709e48b13
|
https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/pairwise.py#L271-L307
|
245,463
|
dossier/dossier.models
|
dossier/models/features/sip.py
|
noun_phrases_as_tokens
|
def noun_phrases_as_tokens(text):
'''Generate a bag of lists of unnormalized tokens representing noun
phrases from ``text``.
This is built around python's nltk library for getting Noun
Phrases (NPs). This is all documented in the NLTK Book
http://www.nltk.org/book/ch03.html and blog posts that cite the
book.
:rtype: list of lists of strings
'''
## from NLTK Book:
sentence_re = r'''(?x) # set flag to allow verbose regexps
([A-Z])(\.[A-Z])+\.? # abbreviations, e.g. U.S.A.
| \w+(-\w+)* # words with optional internal hyphens
| \$?\d+(\.\d+)?%? # currency and percentages, e.g. $12.40, 82%
| \.\.\. # ellipsis
| [][.,;"'?():-_`] # these are separate tokens
'''
## From Su Nam Kim paper:
## http://www.comp.nus.edu.sg/~kanmy/papers/10.1007_s10579-012-9210-3.pdf
grammar = r'''
NBAR:
{<NN.*|JJ>*<NN.*>} # Nouns and Adjectives, terminated with Nouns
NP:
{<NBAR>}
{<NBAR><IN><NBAR>} # Above, connected with in/of/etc...
'''
if len(text.strip()) == 0:
return []
chunker = nltk.RegexpParser(grammar)
toks = nltk.regexp_tokenize(text, sentence_re)
postoks = nltk.tag.pos_tag(toks)
#print postoks
tree = chunker.parse(postoks)
stops = stopwords.words('english')
stops += dossier_stopwords()
## These next four functions are standard uses of NLTK illustrated by
## http://alexbowe.com/au-naturale/
## https://gist.github.com/alexbowe/879414
def leaves(tree):
'''Finds NP (nounphrase) leaf nodes of a chunk tree.'''
for subtree in tree.subtrees(filter = lambda t: t.label()=='NP'):
yield subtree.leaves()
def acceptable_word(word):
'''Checks conditions for acceptable word: length, stopword.'''
return 2 <= len(word) <= 40 and word.lower() not in stops
def get_terms(tree):
for leaf in leaves(tree):
yield [w for w,t in leaf if acceptable_word(w)]
return list(get_terms(tree))
|
python
|
def noun_phrases_as_tokens(text):
'''Generate a bag of lists of unnormalized tokens representing noun
phrases from ``text``.
This is built around python's nltk library for getting Noun
Phrases (NPs). This is all documented in the NLTK Book
http://www.nltk.org/book/ch03.html and blog posts that cite the
book.
:rtype: list of lists of strings
'''
## from NLTK Book:
sentence_re = r'''(?x) # set flag to allow verbose regexps
([A-Z])(\.[A-Z])+\.? # abbreviations, e.g. U.S.A.
| \w+(-\w+)* # words with optional internal hyphens
| \$?\d+(\.\d+)?%? # currency and percentages, e.g. $12.40, 82%
| \.\.\. # ellipsis
| [][.,;"'?():-_`] # these are separate tokens
'''
## From Su Nam Kim paper:
## http://www.comp.nus.edu.sg/~kanmy/papers/10.1007_s10579-012-9210-3.pdf
grammar = r'''
NBAR:
{<NN.*|JJ>*<NN.*>} # Nouns and Adjectives, terminated with Nouns
NP:
{<NBAR>}
{<NBAR><IN><NBAR>} # Above, connected with in/of/etc...
'''
if len(text.strip()) == 0:
return []
chunker = nltk.RegexpParser(grammar)
toks = nltk.regexp_tokenize(text, sentence_re)
postoks = nltk.tag.pos_tag(toks)
#print postoks
tree = chunker.parse(postoks)
stops = stopwords.words('english')
stops += dossier_stopwords()
## These next four functions are standard uses of NLTK illustrated by
## http://alexbowe.com/au-naturale/
## https://gist.github.com/alexbowe/879414
def leaves(tree):
'''Finds NP (nounphrase) leaf nodes of a chunk tree.'''
for subtree in tree.subtrees(filter = lambda t: t.label()=='NP'):
yield subtree.leaves()
def acceptable_word(word):
'''Checks conditions for acceptable word: length, stopword.'''
return 2 <= len(word) <= 40 and word.lower() not in stops
def get_terms(tree):
for leaf in leaves(tree):
yield [w for w,t in leaf if acceptable_word(w)]
return list(get_terms(tree))
|
[
"def",
"noun_phrases_as_tokens",
"(",
"text",
")",
":",
"## from NLTK Book:",
"sentence_re",
"=",
"r'''(?x) # set flag to allow verbose regexps\n ([A-Z])(\\.[A-Z])+\\.? # abbreviations, e.g. U.S.A.\n | \\w+(-\\w+)* # words with optional internal hyphens\n | \\$?\\d+(\\.\\d+)?%? # currency and percentages, e.g. $12.40, 82%\n | \\.\\.\\. # ellipsis\n | [][.,;\"'?():-_`] # these are separate tokens\n '''",
"## From Su Nam Kim paper:",
"## http://www.comp.nus.edu.sg/~kanmy/papers/10.1007_s10579-012-9210-3.pdf",
"grammar",
"=",
"r'''\n NBAR:\n {<NN.*|JJ>*<NN.*>} # Nouns and Adjectives, terminated with Nouns\n\n NP:\n {<NBAR>}\n {<NBAR><IN><NBAR>} # Above, connected with in/of/etc...\n '''",
"if",
"len",
"(",
"text",
".",
"strip",
"(",
")",
")",
"==",
"0",
":",
"return",
"[",
"]",
"chunker",
"=",
"nltk",
".",
"RegexpParser",
"(",
"grammar",
")",
"toks",
"=",
"nltk",
".",
"regexp_tokenize",
"(",
"text",
",",
"sentence_re",
")",
"postoks",
"=",
"nltk",
".",
"tag",
".",
"pos_tag",
"(",
"toks",
")",
"#print postoks",
"tree",
"=",
"chunker",
".",
"parse",
"(",
"postoks",
")",
"stops",
"=",
"stopwords",
".",
"words",
"(",
"'english'",
")",
"stops",
"+=",
"dossier_stopwords",
"(",
")",
"## These next four functions are standard uses of NLTK illustrated by",
"## http://alexbowe.com/au-naturale/",
"## https://gist.github.com/alexbowe/879414",
"def",
"leaves",
"(",
"tree",
")",
":",
"'''Finds NP (nounphrase) leaf nodes of a chunk tree.'''",
"for",
"subtree",
"in",
"tree",
".",
"subtrees",
"(",
"filter",
"=",
"lambda",
"t",
":",
"t",
".",
"label",
"(",
")",
"==",
"'NP'",
")",
":",
"yield",
"subtree",
".",
"leaves",
"(",
")",
"def",
"acceptable_word",
"(",
"word",
")",
":",
"'''Checks conditions for acceptable word: length, stopword.'''",
"return",
"2",
"<=",
"len",
"(",
"word",
")",
"<=",
"40",
"and",
"word",
".",
"lower",
"(",
")",
"not",
"in",
"stops",
"def",
"get_terms",
"(",
"tree",
")",
":",
"for",
"leaf",
"in",
"leaves",
"(",
"tree",
")",
":",
"yield",
"[",
"w",
"for",
"w",
",",
"t",
"in",
"leaf",
"if",
"acceptable_word",
"(",
"w",
")",
"]",
"return",
"list",
"(",
"get_terms",
"(",
"tree",
")",
")"
] |
Generate a bag of lists of unnormalized tokens representing noun
phrases from ``text``.
This is built around python's nltk library for getting Noun
Phrases (NPs). This is all documented in the NLTK Book
http://www.nltk.org/book/ch03.html and blog posts that cite the
book.
:rtype: list of lists of strings
|
[
"Generate",
"a",
"bag",
"of",
"lists",
"of",
"unnormalized",
"tokens",
"representing",
"noun",
"phrases",
"from",
"text",
"."
] |
c9e282f690eab72963926329efe1600709e48b13
|
https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/features/sip.py#L27-L87
|
245,464
|
dossier/dossier.models
|
dossier/models/features/sip.py
|
noun_phrases
|
def noun_phrases(text, included_unnormalized=False):
'''applies normalization to the terms found by noun_phrases_as_tokens
and joins on '_'.
:rtype: list of phrase strings with spaces replaced by ``_``.
'''
lemmatizer = nltk.WordNetLemmatizer()
stemmer = nltk.stem.porter.PorterStemmer()
def normalize(word):
'''Normalises words to lowercase and stems and lemmatizes it.'''
word = word.lower()
try:
word = stemmer.stem_word(word)
word = lemmatizer.lemmatize(word)
except:
pass
return word
normalizations = defaultdict(list)
for terms in noun_phrases_as_tokens(text):
key = u'_'.join(map(normalize, terms))
normalizations[key].append(u' '.join(terms))
if included_unnormalized:
return normalizations.keys(), normalizations
else:
return normalizations.keys()
|
python
|
def noun_phrases(text, included_unnormalized=False):
'''applies normalization to the terms found by noun_phrases_as_tokens
and joins on '_'.
:rtype: list of phrase strings with spaces replaced by ``_``.
'''
lemmatizer = nltk.WordNetLemmatizer()
stemmer = nltk.stem.porter.PorterStemmer()
def normalize(word):
'''Normalises words to lowercase and stems and lemmatizes it.'''
word = word.lower()
try:
word = stemmer.stem_word(word)
word = lemmatizer.lemmatize(word)
except:
pass
return word
normalizations = defaultdict(list)
for terms in noun_phrases_as_tokens(text):
key = u'_'.join(map(normalize, terms))
normalizations[key].append(u' '.join(terms))
if included_unnormalized:
return normalizations.keys(), normalizations
else:
return normalizations.keys()
|
[
"def",
"noun_phrases",
"(",
"text",
",",
"included_unnormalized",
"=",
"False",
")",
":",
"lemmatizer",
"=",
"nltk",
".",
"WordNetLemmatizer",
"(",
")",
"stemmer",
"=",
"nltk",
".",
"stem",
".",
"porter",
".",
"PorterStemmer",
"(",
")",
"def",
"normalize",
"(",
"word",
")",
":",
"'''Normalises words to lowercase and stems and lemmatizes it.'''",
"word",
"=",
"word",
".",
"lower",
"(",
")",
"try",
":",
"word",
"=",
"stemmer",
".",
"stem_word",
"(",
"word",
")",
"word",
"=",
"lemmatizer",
".",
"lemmatize",
"(",
"word",
")",
"except",
":",
"pass",
"return",
"word",
"normalizations",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"terms",
"in",
"noun_phrases_as_tokens",
"(",
"text",
")",
":",
"key",
"=",
"u'_'",
".",
"join",
"(",
"map",
"(",
"normalize",
",",
"terms",
")",
")",
"normalizations",
"[",
"key",
"]",
".",
"append",
"(",
"u' '",
".",
"join",
"(",
"terms",
")",
")",
"if",
"included_unnormalized",
":",
"return",
"normalizations",
".",
"keys",
"(",
")",
",",
"normalizations",
"else",
":",
"return",
"normalizations",
".",
"keys",
"(",
")"
] |
applies normalization to the terms found by noun_phrases_as_tokens
and joins on '_'.
:rtype: list of phrase strings with spaces replaced by ``_``.
|
[
"applies",
"normalization",
"to",
"the",
"terms",
"found",
"by",
"noun_phrases_as_tokens",
"and",
"joins",
"on",
"_",
"."
] |
c9e282f690eab72963926329efe1600709e48b13
|
https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/features/sip.py#L90-L118
|
245,465
|
crypto101/clarent
|
clarent/certificate.py
|
_makeCertificate
|
def _makeCertificate(key, email, _utcnow=datetime.utcnow):
"""Make the certificate for the client using the given key and e-mail
address.
"""
# Create a certificate for this key.
cert = X509()
cert.set_pubkey(key)
# Set the subject.
subject = cert.get_subject()
subject.CN = u"Crypto 101 Client"
subject.emailAddress = email
# Expiration dates. Mandatory.
now = _utcnow()
start = now.replace(hour=0, minute=0, second=0)
cert.set_notBefore(start.strftime(_ASN1_GENERALIZEDTIME_FORMAT))
end = start.replace(year=start.year + 5)
cert.set_notAfter(end.strftime(_ASN1_GENERALIZEDTIME_FORMAT))
# Self-sign.
cert.set_issuer(cert.get_subject())
cert.sign(key, "sha512")
return cert
|
python
|
def _makeCertificate(key, email, _utcnow=datetime.utcnow):
"""Make the certificate for the client using the given key and e-mail
address.
"""
# Create a certificate for this key.
cert = X509()
cert.set_pubkey(key)
# Set the subject.
subject = cert.get_subject()
subject.CN = u"Crypto 101 Client"
subject.emailAddress = email
# Expiration dates. Mandatory.
now = _utcnow()
start = now.replace(hour=0, minute=0, second=0)
cert.set_notBefore(start.strftime(_ASN1_GENERALIZEDTIME_FORMAT))
end = start.replace(year=start.year + 5)
cert.set_notAfter(end.strftime(_ASN1_GENERALIZEDTIME_FORMAT))
# Self-sign.
cert.set_issuer(cert.get_subject())
cert.sign(key, "sha512")
return cert
|
[
"def",
"_makeCertificate",
"(",
"key",
",",
"email",
",",
"_utcnow",
"=",
"datetime",
".",
"utcnow",
")",
":",
"# Create a certificate for this key.",
"cert",
"=",
"X509",
"(",
")",
"cert",
".",
"set_pubkey",
"(",
"key",
")",
"# Set the subject.",
"subject",
"=",
"cert",
".",
"get_subject",
"(",
")",
"subject",
".",
"CN",
"=",
"u\"Crypto 101 Client\"",
"subject",
".",
"emailAddress",
"=",
"email",
"# Expiration dates. Mandatory.",
"now",
"=",
"_utcnow",
"(",
")",
"start",
"=",
"now",
".",
"replace",
"(",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
")",
"cert",
".",
"set_notBefore",
"(",
"start",
".",
"strftime",
"(",
"_ASN1_GENERALIZEDTIME_FORMAT",
")",
")",
"end",
"=",
"start",
".",
"replace",
"(",
"year",
"=",
"start",
".",
"year",
"+",
"5",
")",
"cert",
".",
"set_notAfter",
"(",
"end",
".",
"strftime",
"(",
"_ASN1_GENERALIZEDTIME_FORMAT",
")",
")",
"# Self-sign.",
"cert",
".",
"set_issuer",
"(",
"cert",
".",
"get_subject",
"(",
")",
")",
"cert",
".",
"sign",
"(",
"key",
",",
"\"sha512\"",
")",
"return",
"cert"
] |
Make the certificate for the client using the given key and e-mail
address.
|
[
"Make",
"the",
"certificate",
"for",
"the",
"client",
"using",
"the",
"given",
"key",
"and",
"e",
"-",
"mail",
"address",
"."
] |
2b441d7933e85ee948cfb78506b7ca0a32e9588d
|
https://github.com/crypto101/clarent/blob/2b441d7933e85ee948cfb78506b7ca0a32e9588d/clarent/certificate.py#L19-L44
|
245,466
|
crypto101/clarent
|
clarent/certificate.py
|
makeCredentials
|
def makeCredentials(path, email):
"""Make credentials for the client from given e-mail address and store
them in the directory at path.
"""
key = _generateKey()
cert = _makeCertificate(key, email)
certPath = path.child("client.pem")
certPath.alwaysCreate = True
with certPath.open("wb") as pemFile:
pemFile.write(dump_privatekey(FILETYPE_PEM, key))
pemFile.write(dump_certificate(FILETYPE_PEM, cert))
|
python
|
def makeCredentials(path, email):
"""Make credentials for the client from given e-mail address and store
them in the directory at path.
"""
key = _generateKey()
cert = _makeCertificate(key, email)
certPath = path.child("client.pem")
certPath.alwaysCreate = True
with certPath.open("wb") as pemFile:
pemFile.write(dump_privatekey(FILETYPE_PEM, key))
pemFile.write(dump_certificate(FILETYPE_PEM, cert))
|
[
"def",
"makeCredentials",
"(",
"path",
",",
"email",
")",
":",
"key",
"=",
"_generateKey",
"(",
")",
"cert",
"=",
"_makeCertificate",
"(",
"key",
",",
"email",
")",
"certPath",
"=",
"path",
".",
"child",
"(",
"\"client.pem\"",
")",
"certPath",
".",
"alwaysCreate",
"=",
"True",
"with",
"certPath",
".",
"open",
"(",
"\"wb\"",
")",
"as",
"pemFile",
":",
"pemFile",
".",
"write",
"(",
"dump_privatekey",
"(",
"FILETYPE_PEM",
",",
"key",
")",
")",
"pemFile",
".",
"write",
"(",
"dump_certificate",
"(",
"FILETYPE_PEM",
",",
"cert",
")",
")"
] |
Make credentials for the client from given e-mail address and store
them in the directory at path.
|
[
"Make",
"credentials",
"for",
"the",
"client",
"from",
"given",
"e",
"-",
"mail",
"address",
"and",
"store",
"them",
"in",
"the",
"directory",
"at",
"path",
"."
] |
2b441d7933e85ee948cfb78506b7ca0a32e9588d
|
https://github.com/crypto101/clarent/blob/2b441d7933e85ee948cfb78506b7ca0a32e9588d/clarent/certificate.py#L59-L72
|
245,467
|
crypto101/clarent
|
clarent/certificate.py
|
getContextFactory
|
def getContextFactory(path):
"""Get a context factory for the client from keys already stored at
path.
Raises IOError if the credentials didn't exist.
"""
with path.child("client.pem").open() as pemFile:
cert = PrivateCertificate.loadPEM(pemFile.read())
certOptions = cert.options() # TODO: verify server cert (see #1)
certOptions.method = SSL.SSLv23_METHOD
ctxFactory = SecureCiphersContextFactory(certOptions)
return ctxFactory
|
python
|
def getContextFactory(path):
"""Get a context factory for the client from keys already stored at
path.
Raises IOError if the credentials didn't exist.
"""
with path.child("client.pem").open() as pemFile:
cert = PrivateCertificate.loadPEM(pemFile.read())
certOptions = cert.options() # TODO: verify server cert (see #1)
certOptions.method = SSL.SSLv23_METHOD
ctxFactory = SecureCiphersContextFactory(certOptions)
return ctxFactory
|
[
"def",
"getContextFactory",
"(",
"path",
")",
":",
"with",
"path",
".",
"child",
"(",
"\"client.pem\"",
")",
".",
"open",
"(",
")",
"as",
"pemFile",
":",
"cert",
"=",
"PrivateCertificate",
".",
"loadPEM",
"(",
"pemFile",
".",
"read",
"(",
")",
")",
"certOptions",
"=",
"cert",
".",
"options",
"(",
")",
"# TODO: verify server cert (see #1)",
"certOptions",
".",
"method",
"=",
"SSL",
".",
"SSLv23_METHOD",
"ctxFactory",
"=",
"SecureCiphersContextFactory",
"(",
"certOptions",
")",
"return",
"ctxFactory"
] |
Get a context factory for the client from keys already stored at
path.
Raises IOError if the credentials didn't exist.
|
[
"Get",
"a",
"context",
"factory",
"for",
"the",
"client",
"from",
"keys",
"already",
"stored",
"at",
"path",
"."
] |
2b441d7933e85ee948cfb78506b7ca0a32e9588d
|
https://github.com/crypto101/clarent/blob/2b441d7933e85ee948cfb78506b7ca0a32e9588d/clarent/certificate.py#L76-L89
|
245,468
|
kankiri/pabiana
|
demos/smarthome/smarthome/__init__.py
|
schedule
|
def schedule(demand: dict, alterations: set, looped: set=None, altered: set=None):
"""Prioritizes Triggers called from outside."""
if looped is not None and len(demand) != len(looped):
for func in looped: del demand[func]
if keep_temp in demand:
demand.pop(increase_temp, None)
demand.pop(lower_temp, None)
elif lower_temp in demand:
demand.pop(increase_temp, None)
return demand, alterations
|
python
|
def schedule(demand: dict, alterations: set, looped: set=None, altered: set=None):
"""Prioritizes Triggers called from outside."""
if looped is not None and len(demand) != len(looped):
for func in looped: del demand[func]
if keep_temp in demand:
demand.pop(increase_temp, None)
demand.pop(lower_temp, None)
elif lower_temp in demand:
demand.pop(increase_temp, None)
return demand, alterations
|
[
"def",
"schedule",
"(",
"demand",
":",
"dict",
",",
"alterations",
":",
"set",
",",
"looped",
":",
"set",
"=",
"None",
",",
"altered",
":",
"set",
"=",
"None",
")",
":",
"if",
"looped",
"is",
"not",
"None",
"and",
"len",
"(",
"demand",
")",
"!=",
"len",
"(",
"looped",
")",
":",
"for",
"func",
"in",
"looped",
":",
"del",
"demand",
"[",
"func",
"]",
"if",
"keep_temp",
"in",
"demand",
":",
"demand",
".",
"pop",
"(",
"increase_temp",
",",
"None",
")",
"demand",
".",
"pop",
"(",
"lower_temp",
",",
"None",
")",
"elif",
"lower_temp",
"in",
"demand",
":",
"demand",
".",
"pop",
"(",
"increase_temp",
",",
"None",
")",
"return",
"demand",
",",
"alterations"
] |
Prioritizes Triggers called from outside.
|
[
"Prioritizes",
"Triggers",
"called",
"from",
"outside",
"."
] |
74acfdd81e2a1cc411c37b9ee3d6905ce4b1a39b
|
https://github.com/kankiri/pabiana/blob/74acfdd81e2a1cc411c37b9ee3d6905ce4b1a39b/demos/smarthome/smarthome/__init__.py#L41-L50
|
245,469
|
cykerway/logging-ext
|
logging_ext/__init__.py
|
d
|
def d(msg, *args, **kwargs):
'''
log a message at debug level;
'''
return logging.log(DEBUG, msg, *args, **kwargs)
|
python
|
def d(msg, *args, **kwargs):
'''
log a message at debug level;
'''
return logging.log(DEBUG, msg, *args, **kwargs)
|
[
"def",
"d",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"logging",
".",
"log",
"(",
"DEBUG",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
log a message at debug level;
|
[
"log",
"a",
"message",
"at",
"debug",
"level",
";"
] |
ed6700bdd602fa26276e1f194d255e74c7f255b4
|
https://github.com/cykerway/logging-ext/blob/ed6700bdd602fa26276e1f194d255e74c7f255b4/logging_ext/__init__.py#L24-L30
|
245,470
|
cykerway/logging-ext
|
logging_ext/__init__.py
|
v
|
def v(msg, *args, **kwargs):
'''
log a message at verbose level;
'''
return logging.log(VERBOSE, msg, *args, **kwargs)
|
python
|
def v(msg, *args, **kwargs):
'''
log a message at verbose level;
'''
return logging.log(VERBOSE, msg, *args, **kwargs)
|
[
"def",
"v",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"logging",
".",
"log",
"(",
"VERBOSE",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
log a message at verbose level;
|
[
"log",
"a",
"message",
"at",
"verbose",
"level",
";"
] |
ed6700bdd602fa26276e1f194d255e74c7f255b4
|
https://github.com/cykerway/logging-ext/blob/ed6700bdd602fa26276e1f194d255e74c7f255b4/logging_ext/__init__.py#L32-L38
|
245,471
|
cykerway/logging-ext
|
logging_ext/__init__.py
|
i
|
def i(msg, *args, **kwargs):
'''
log a message at info level;
'''
return logging.log(INFO, msg, *args, **kwargs)
|
python
|
def i(msg, *args, **kwargs):
'''
log a message at info level;
'''
return logging.log(INFO, msg, *args, **kwargs)
|
[
"def",
"i",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"logging",
".",
"log",
"(",
"INFO",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
log a message at info level;
|
[
"log",
"a",
"message",
"at",
"info",
"level",
";"
] |
ed6700bdd602fa26276e1f194d255e74c7f255b4
|
https://github.com/cykerway/logging-ext/blob/ed6700bdd602fa26276e1f194d255e74c7f255b4/logging_ext/__init__.py#L40-L46
|
245,472
|
cykerway/logging-ext
|
logging_ext/__init__.py
|
w
|
def w(msg, *args, **kwargs):
'''
log a message at warn level;
'''
return logging.log(WARN, msg, *args, **kwargs)
|
python
|
def w(msg, *args, **kwargs):
'''
log a message at warn level;
'''
return logging.log(WARN, msg, *args, **kwargs)
|
[
"def",
"w",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"logging",
".",
"log",
"(",
"WARN",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
log a message at warn level;
|
[
"log",
"a",
"message",
"at",
"warn",
"level",
";"
] |
ed6700bdd602fa26276e1f194d255e74c7f255b4
|
https://github.com/cykerway/logging-ext/blob/ed6700bdd602fa26276e1f194d255e74c7f255b4/logging_ext/__init__.py#L48-L54
|
245,473
|
cykerway/logging-ext
|
logging_ext/__init__.py
|
e
|
def e(msg, *args, **kwargs):
'''
log a message at error level;
'''
return logging.log(ERROR, msg, *args, **kwargs)
|
python
|
def e(msg, *args, **kwargs):
'''
log a message at error level;
'''
return logging.log(ERROR, msg, *args, **kwargs)
|
[
"def",
"e",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"logging",
".",
"log",
"(",
"ERROR",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
log a message at error level;
|
[
"log",
"a",
"message",
"at",
"error",
"level",
";"
] |
ed6700bdd602fa26276e1f194d255e74c7f255b4
|
https://github.com/cykerway/logging-ext/blob/ed6700bdd602fa26276e1f194d255e74c7f255b4/logging_ext/__init__.py#L56-L62
|
245,474
|
cykerway/logging-ext
|
logging_ext/__init__.py
|
getLogger
|
def getLogger(name=None):
'''
return a logger instrumented with additional 1-letter logging methods;
'''
logger = logging.getLogger(name=name)
if not hasattr(logger, 'd'):
def d(self, msg, *args, **kwargs):
return self.log(DEBUG, msg, *args, **kwargs)
logger.d = types.MethodType(d, logger)
if not hasattr(logger, 'v'):
def v(self, msg, *args, **kwargs):
return self.log(VERBOSE, msg, *args, **kwargs)
logger.v = types.MethodType(v, logger)
if not hasattr(logger, 'i'):
def i(self, msg, *args, **kwargs):
return self.log(INFO, msg, *args, **kwargs)
logger.i = types.MethodType(i, logger)
if not hasattr(logger, 'w'):
def w(self, msg, *args, **kwargs):
return self.log(WARN, msg, *args, **kwargs)
logger.w = types.MethodType(w, logger)
if not hasattr(logger, 'e'):
def e(self, msg, *args, **kwargs):
return self.log(ERROR, msg, *args, **kwargs)
logger.e = types.MethodType(e, logger)
return logger
|
python
|
def getLogger(name=None):
'''
return a logger instrumented with additional 1-letter logging methods;
'''
logger = logging.getLogger(name=name)
if not hasattr(logger, 'd'):
def d(self, msg, *args, **kwargs):
return self.log(DEBUG, msg, *args, **kwargs)
logger.d = types.MethodType(d, logger)
if not hasattr(logger, 'v'):
def v(self, msg, *args, **kwargs):
return self.log(VERBOSE, msg, *args, **kwargs)
logger.v = types.MethodType(v, logger)
if not hasattr(logger, 'i'):
def i(self, msg, *args, **kwargs):
return self.log(INFO, msg, *args, **kwargs)
logger.i = types.MethodType(i, logger)
if not hasattr(logger, 'w'):
def w(self, msg, *args, **kwargs):
return self.log(WARN, msg, *args, **kwargs)
logger.w = types.MethodType(w, logger)
if not hasattr(logger, 'e'):
def e(self, msg, *args, **kwargs):
return self.log(ERROR, msg, *args, **kwargs)
logger.e = types.MethodType(e, logger)
return logger
|
[
"def",
"getLogger",
"(",
"name",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
"=",
"name",
")",
"if",
"not",
"hasattr",
"(",
"logger",
",",
"'d'",
")",
":",
"def",
"d",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"log",
"(",
"DEBUG",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"logger",
".",
"d",
"=",
"types",
".",
"MethodType",
"(",
"d",
",",
"logger",
")",
"if",
"not",
"hasattr",
"(",
"logger",
",",
"'v'",
")",
":",
"def",
"v",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"log",
"(",
"VERBOSE",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"logger",
".",
"v",
"=",
"types",
".",
"MethodType",
"(",
"v",
",",
"logger",
")",
"if",
"not",
"hasattr",
"(",
"logger",
",",
"'i'",
")",
":",
"def",
"i",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"log",
"(",
"INFO",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"logger",
".",
"i",
"=",
"types",
".",
"MethodType",
"(",
"i",
",",
"logger",
")",
"if",
"not",
"hasattr",
"(",
"logger",
",",
"'w'",
")",
":",
"def",
"w",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"log",
"(",
"WARN",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"logger",
".",
"w",
"=",
"types",
".",
"MethodType",
"(",
"w",
",",
"logger",
")",
"if",
"not",
"hasattr",
"(",
"logger",
",",
"'e'",
")",
":",
"def",
"e",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"log",
"(",
"ERROR",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"logger",
".",
"e",
"=",
"types",
".",
"MethodType",
"(",
"e",
",",
"logger",
")",
"return",
"logger"
] |
return a logger instrumented with additional 1-letter logging methods;
|
[
"return",
"a",
"logger",
"instrumented",
"with",
"additional",
"1",
"-",
"letter",
"logging",
"methods",
";"
] |
ed6700bdd602fa26276e1f194d255e74c7f255b4
|
https://github.com/cykerway/logging-ext/blob/ed6700bdd602fa26276e1f194d255e74c7f255b4/logging_ext/__init__.py#L68-L101
|
245,475
|
Diaoul/pyextdirect
|
pyextdirect/router.py
|
create_instances
|
def create_instances(configuration):
"""Create necessary class instances from a configuration with no argument to the constructor
:param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration`
:return: a class-instance mapping
:rtype: dict
"""
instances = {}
for methods in configuration.itervalues():
for element in methods.itervalues():
if not isinstance(element, tuple):
continue
cls, _ = element
if cls not in instances:
instances[cls] = cls()
return instances
|
python
|
def create_instances(configuration):
"""Create necessary class instances from a configuration with no argument to the constructor
:param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration`
:return: a class-instance mapping
:rtype: dict
"""
instances = {}
for methods in configuration.itervalues():
for element in methods.itervalues():
if not isinstance(element, tuple):
continue
cls, _ = element
if cls not in instances:
instances[cls] = cls()
return instances
|
[
"def",
"create_instances",
"(",
"configuration",
")",
":",
"instances",
"=",
"{",
"}",
"for",
"methods",
"in",
"configuration",
".",
"itervalues",
"(",
")",
":",
"for",
"element",
"in",
"methods",
".",
"itervalues",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"element",
",",
"tuple",
")",
":",
"continue",
"cls",
",",
"_",
"=",
"element",
"if",
"cls",
"not",
"in",
"instances",
":",
"instances",
"[",
"cls",
"]",
"=",
"cls",
"(",
")",
"return",
"instances"
] |
Create necessary class instances from a configuration with no argument to the constructor
:param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration`
:return: a class-instance mapping
:rtype: dict
|
[
"Create",
"necessary",
"class",
"instances",
"from",
"a",
"configuration",
"with",
"no",
"argument",
"to",
"the",
"constructor"
] |
34ddfe882d467b3769644e8131fb90fe472eff80
|
https://github.com/Diaoul/pyextdirect/blob/34ddfe882d467b3769644e8131fb90fe472eff80/pyextdirect/router.py#L117-L133
|
245,476
|
Diaoul/pyextdirect
|
pyextdirect/router.py
|
Router.call
|
def call(self, request):
"""Call the appropriate function
:param dict request: request that describes the function to call
:return: response linked to the request that holds the value returned by the called function
:rtype: dict
"""
result = None
try:
if 'extAction' in request: # DirectSubmit method
tid = request['extTID']
action = request['extAction']
method = request['extMethod']
else:
tid = request['tid']
action = request['action']
method = request['method']
element = self.configuration[action][method]
if isinstance(element, tuple): # class level function
func = getattr(self.instances[element[0]], element[1])
else: # module level function
func = element
if func.exposed_kind == BASIC: # basic method
args = request['data'] or []
result = func(*args)
elif func.exposed_kind == LOAD: # DirectLoad method
args = request['data'] or []
result = {'success': True, 'data': func(*args)}
elif func.exposed_kind == SUBMIT: # DirectSubmit method
kwargs = request
for k in ['extAction', 'extMethod', 'extType', 'extTID', 'extUpload']:
if k in kwargs:
del kwargs[k]
try:
func(**kwargs)
result = {'success': True}
except FormError as e:
result = e.extra
result['success'] = False
if e.errors:
result['errors'] = e.errors
elif func.exposed_kind == STORE_READ: # DirectStore read method
kwargs = request['data'] or {}
data = func(**kwargs)
result = {'total': len(data), 'data': data}
elif func.exposed_kind == STORE_CUD: # DirectStore create-update-destroy methods
kwargs = request['data'][0] or {}
try:
result = {'success': True, 'data': func(**kwargs)}
except Error:
result = {'success': False}
except Exception as e:
if self.debug:
return {'type': 'exception', 'message': str(e), 'where': '%s.%s' % (action, method)}
return {'type': 'rpc', 'tid': tid, 'action': action, 'method': method, 'result': result}
|
python
|
def call(self, request):
"""Call the appropriate function
:param dict request: request that describes the function to call
:return: response linked to the request that holds the value returned by the called function
:rtype: dict
"""
result = None
try:
if 'extAction' in request: # DirectSubmit method
tid = request['extTID']
action = request['extAction']
method = request['extMethod']
else:
tid = request['tid']
action = request['action']
method = request['method']
element = self.configuration[action][method]
if isinstance(element, tuple): # class level function
func = getattr(self.instances[element[0]], element[1])
else: # module level function
func = element
if func.exposed_kind == BASIC: # basic method
args = request['data'] or []
result = func(*args)
elif func.exposed_kind == LOAD: # DirectLoad method
args = request['data'] or []
result = {'success': True, 'data': func(*args)}
elif func.exposed_kind == SUBMIT: # DirectSubmit method
kwargs = request
for k in ['extAction', 'extMethod', 'extType', 'extTID', 'extUpload']:
if k in kwargs:
del kwargs[k]
try:
func(**kwargs)
result = {'success': True}
except FormError as e:
result = e.extra
result['success'] = False
if e.errors:
result['errors'] = e.errors
elif func.exposed_kind == STORE_READ: # DirectStore read method
kwargs = request['data'] or {}
data = func(**kwargs)
result = {'total': len(data), 'data': data}
elif func.exposed_kind == STORE_CUD: # DirectStore create-update-destroy methods
kwargs = request['data'][0] or {}
try:
result = {'success': True, 'data': func(**kwargs)}
except Error:
result = {'success': False}
except Exception as e:
if self.debug:
return {'type': 'exception', 'message': str(e), 'where': '%s.%s' % (action, method)}
return {'type': 'rpc', 'tid': tid, 'action': action, 'method': method, 'result': result}
|
[
"def",
"call",
"(",
"self",
",",
"request",
")",
":",
"result",
"=",
"None",
"try",
":",
"if",
"'extAction'",
"in",
"request",
":",
"# DirectSubmit method",
"tid",
"=",
"request",
"[",
"'extTID'",
"]",
"action",
"=",
"request",
"[",
"'extAction'",
"]",
"method",
"=",
"request",
"[",
"'extMethod'",
"]",
"else",
":",
"tid",
"=",
"request",
"[",
"'tid'",
"]",
"action",
"=",
"request",
"[",
"'action'",
"]",
"method",
"=",
"request",
"[",
"'method'",
"]",
"element",
"=",
"self",
".",
"configuration",
"[",
"action",
"]",
"[",
"method",
"]",
"if",
"isinstance",
"(",
"element",
",",
"tuple",
")",
":",
"# class level function",
"func",
"=",
"getattr",
"(",
"self",
".",
"instances",
"[",
"element",
"[",
"0",
"]",
"]",
",",
"element",
"[",
"1",
"]",
")",
"else",
":",
"# module level function",
"func",
"=",
"element",
"if",
"func",
".",
"exposed_kind",
"==",
"BASIC",
":",
"# basic method",
"args",
"=",
"request",
"[",
"'data'",
"]",
"or",
"[",
"]",
"result",
"=",
"func",
"(",
"*",
"args",
")",
"elif",
"func",
".",
"exposed_kind",
"==",
"LOAD",
":",
"# DirectLoad method",
"args",
"=",
"request",
"[",
"'data'",
"]",
"or",
"[",
"]",
"result",
"=",
"{",
"'success'",
":",
"True",
",",
"'data'",
":",
"func",
"(",
"*",
"args",
")",
"}",
"elif",
"func",
".",
"exposed_kind",
"==",
"SUBMIT",
":",
"# DirectSubmit method",
"kwargs",
"=",
"request",
"for",
"k",
"in",
"[",
"'extAction'",
",",
"'extMethod'",
",",
"'extType'",
",",
"'extTID'",
",",
"'extUpload'",
"]",
":",
"if",
"k",
"in",
"kwargs",
":",
"del",
"kwargs",
"[",
"k",
"]",
"try",
":",
"func",
"(",
"*",
"*",
"kwargs",
")",
"result",
"=",
"{",
"'success'",
":",
"True",
"}",
"except",
"FormError",
"as",
"e",
":",
"result",
"=",
"e",
".",
"extra",
"result",
"[",
"'success'",
"]",
"=",
"False",
"if",
"e",
".",
"errors",
":",
"result",
"[",
"'errors'",
"]",
"=",
"e",
".",
"errors",
"elif",
"func",
".",
"exposed_kind",
"==",
"STORE_READ",
":",
"# DirectStore read method",
"kwargs",
"=",
"request",
"[",
"'data'",
"]",
"or",
"{",
"}",
"data",
"=",
"func",
"(",
"*",
"*",
"kwargs",
")",
"result",
"=",
"{",
"'total'",
":",
"len",
"(",
"data",
")",
",",
"'data'",
":",
"data",
"}",
"elif",
"func",
".",
"exposed_kind",
"==",
"STORE_CUD",
":",
"# DirectStore create-update-destroy methods",
"kwargs",
"=",
"request",
"[",
"'data'",
"]",
"[",
"0",
"]",
"or",
"{",
"}",
"try",
":",
"result",
"=",
"{",
"'success'",
":",
"True",
",",
"'data'",
":",
"func",
"(",
"*",
"*",
"kwargs",
")",
"}",
"except",
"Error",
":",
"result",
"=",
"{",
"'success'",
":",
"False",
"}",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"debug",
":",
"return",
"{",
"'type'",
":",
"'exception'",
",",
"'message'",
":",
"str",
"(",
"e",
")",
",",
"'where'",
":",
"'%s.%s'",
"%",
"(",
"action",
",",
"method",
")",
"}",
"return",
"{",
"'type'",
":",
"'rpc'",
",",
"'tid'",
":",
"tid",
",",
"'action'",
":",
"action",
",",
"'method'",
":",
"method",
",",
"'result'",
":",
"result",
"}"
] |
Call the appropriate function
:param dict request: request that describes the function to call
:return: response linked to the request that holds the value returned by the called function
:rtype: dict
|
[
"Call",
"the",
"appropriate",
"function"
] |
34ddfe882d467b3769644e8131fb90fe472eff80
|
https://github.com/Diaoul/pyextdirect/blob/34ddfe882d467b3769644e8131fb90fe472eff80/pyextdirect/router.py#L59-L114
|
245,477
|
lambdalisue/django-roughpages
|
src/roughpages/utils.py
|
url_to_filename
|
def url_to_filename(url):
"""
Safely translate url to relative filename
Args:
url (str): A target url string
Returns:
str
"""
# remove leading/trailing slash
if url.startswith('/'):
url = url[1:]
if url.endswith('/'):
url = url[:-1]
# remove pardir symbols to prevent unwilling filesystem access
url = remove_pardir_symbols(url)
# replace dots to underscore in filename part
url = replace_dots_to_underscores_at_last(url)
return url
|
python
|
def url_to_filename(url):
"""
Safely translate url to relative filename
Args:
url (str): A target url string
Returns:
str
"""
# remove leading/trailing slash
if url.startswith('/'):
url = url[1:]
if url.endswith('/'):
url = url[:-1]
# remove pardir symbols to prevent unwilling filesystem access
url = remove_pardir_symbols(url)
# replace dots to underscore in filename part
url = replace_dots_to_underscores_at_last(url)
return url
|
[
"def",
"url_to_filename",
"(",
"url",
")",
":",
"# remove leading/trailing slash",
"if",
"url",
".",
"startswith",
"(",
"'/'",
")",
":",
"url",
"=",
"url",
"[",
"1",
":",
"]",
"if",
"url",
".",
"endswith",
"(",
"'/'",
")",
":",
"url",
"=",
"url",
"[",
":",
"-",
"1",
"]",
"# remove pardir symbols to prevent unwilling filesystem access",
"url",
"=",
"remove_pardir_symbols",
"(",
"url",
")",
"# replace dots to underscore in filename part",
"url",
"=",
"replace_dots_to_underscores_at_last",
"(",
"url",
")",
"return",
"url"
] |
Safely translate url to relative filename
Args:
url (str): A target url string
Returns:
str
|
[
"Safely",
"translate",
"url",
"to",
"relative",
"filename"
] |
f6a2724ece729c5deced2c2546d172561ef785ec
|
https://github.com/lambdalisue/django-roughpages/blob/f6a2724ece729c5deced2c2546d172561ef785ec/src/roughpages/utils.py#L8-L27
|
245,478
|
lambdalisue/django-roughpages
|
src/roughpages/utils.py
|
remove_pardir_symbols
|
def remove_pardir_symbols(path, sep=os.sep, pardir=os.pardir):
"""
Remove relative path symobls such as '..'
Args:
path (str): A target path string
sep (str): A strint to refer path delimiter (Default: `os.sep`)
pardir (str): A string to refer parent directory (Default: `os.pardir`)
Returns:
str
"""
bits = path.split(sep)
bits = (x for x in bits if x != pardir)
return sep.join(bits)
|
python
|
def remove_pardir_symbols(path, sep=os.sep, pardir=os.pardir):
"""
Remove relative path symobls such as '..'
Args:
path (str): A target path string
sep (str): A strint to refer path delimiter (Default: `os.sep`)
pardir (str): A string to refer parent directory (Default: `os.pardir`)
Returns:
str
"""
bits = path.split(sep)
bits = (x for x in bits if x != pardir)
return sep.join(bits)
|
[
"def",
"remove_pardir_symbols",
"(",
"path",
",",
"sep",
"=",
"os",
".",
"sep",
",",
"pardir",
"=",
"os",
".",
"pardir",
")",
":",
"bits",
"=",
"path",
".",
"split",
"(",
"sep",
")",
"bits",
"=",
"(",
"x",
"for",
"x",
"in",
"bits",
"if",
"x",
"!=",
"pardir",
")",
"return",
"sep",
".",
"join",
"(",
"bits",
")"
] |
Remove relative path symobls such as '..'
Args:
path (str): A target path string
sep (str): A strint to refer path delimiter (Default: `os.sep`)
pardir (str): A string to refer parent directory (Default: `os.pardir`)
Returns:
str
|
[
"Remove",
"relative",
"path",
"symobls",
"such",
"as",
".."
] |
f6a2724ece729c5deced2c2546d172561ef785ec
|
https://github.com/lambdalisue/django-roughpages/blob/f6a2724ece729c5deced2c2546d172561ef785ec/src/roughpages/utils.py#L30-L44
|
245,479
|
pyokagan/pyglreg
|
glreg.py
|
_load
|
def _load(root):
"""Load from an xml.etree.ElementTree"""
types = _load_types(root)
enums = _load_enums(root)
commands = _load_commands(root)
features = _load_features(root)
extensions = _load_extensions(root)
return Registry(None, types, enums, commands, features, extensions)
|
python
|
def _load(root):
"""Load from an xml.etree.ElementTree"""
types = _load_types(root)
enums = _load_enums(root)
commands = _load_commands(root)
features = _load_features(root)
extensions = _load_extensions(root)
return Registry(None, types, enums, commands, features, extensions)
|
[
"def",
"_load",
"(",
"root",
")",
":",
"types",
"=",
"_load_types",
"(",
"root",
")",
"enums",
"=",
"_load_enums",
"(",
"root",
")",
"commands",
"=",
"_load_commands",
"(",
"root",
")",
"features",
"=",
"_load_features",
"(",
"root",
")",
"extensions",
"=",
"_load_extensions",
"(",
"root",
")",
"return",
"Registry",
"(",
"None",
",",
"types",
",",
"enums",
",",
"commands",
",",
"features",
",",
"extensions",
")"
] |
Load from an xml.etree.ElementTree
|
[
"Load",
"from",
"an",
"xml",
".",
"etree",
".",
"ElementTree"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L616-L623
|
245,480
|
pyokagan/pyglreg
|
glreg.py
|
import_type
|
def import_type(dest, src, name, api=None, filter_symbol=None):
"""Import Type `name` and its dependencies from Registry `src`
to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of type to import
:param str api: Prefer to import Types with api Name `api`, or None to
import Types with no api name.
:param filter_symbol: Optional filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
"""
if not filter_symbol:
filter_symbol = _default_filter_symbol
type = src.get_type(name, api)
for x in type.required_types:
if not filter_symbol('type', x):
continue
import_type(dest, src, x, api, filter_symbol)
dest.types[(type.name, type.api)] = type
|
python
|
def import_type(dest, src, name, api=None, filter_symbol=None):
"""Import Type `name` and its dependencies from Registry `src`
to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of type to import
:param str api: Prefer to import Types with api Name `api`, or None to
import Types with no api name.
:param filter_symbol: Optional filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
"""
if not filter_symbol:
filter_symbol = _default_filter_symbol
type = src.get_type(name, api)
for x in type.required_types:
if not filter_symbol('type', x):
continue
import_type(dest, src, x, api, filter_symbol)
dest.types[(type.name, type.api)] = type
|
[
"def",
"import_type",
"(",
"dest",
",",
"src",
",",
"name",
",",
"api",
"=",
"None",
",",
"filter_symbol",
"=",
"None",
")",
":",
"if",
"not",
"filter_symbol",
":",
"filter_symbol",
"=",
"_default_filter_symbol",
"type",
"=",
"src",
".",
"get_type",
"(",
"name",
",",
"api",
")",
"for",
"x",
"in",
"type",
".",
"required_types",
":",
"if",
"not",
"filter_symbol",
"(",
"'type'",
",",
"x",
")",
":",
"continue",
"import_type",
"(",
"dest",
",",
"src",
",",
"x",
",",
"api",
",",
"filter_symbol",
")",
"dest",
".",
"types",
"[",
"(",
"type",
".",
"name",
",",
"type",
".",
"api",
")",
"]",
"=",
"type"
] |
Import Type `name` and its dependencies from Registry `src`
to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of type to import
:param str api: Prefer to import Types with api Name `api`, or None to
import Types with no api name.
:param filter_symbol: Optional filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
|
[
"Import",
"Type",
"name",
"and",
"its",
"dependencies",
"from",
"Registry",
"src",
"to",
"Registry",
"dest",
"."
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L794-L814
|
245,481
|
pyokagan/pyglreg
|
glreg.py
|
import_command
|
def import_command(dest, src, name, api=None, filter_symbol=None):
"""Import Command `name` and its dependencies from Registry `src`
to Registry `dest`
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Command to import
:param str api: Prefer to import Types with api name `api`, or None to
import Types with no api name
:param filter_symbol: Optional filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
"""
if not filter_symbol:
filter_symbol = _default_filter_symbol
cmd = src.commands[name]
for x in cmd.required_types:
if not filter_symbol('type', x):
continue
import_type(dest, src, x, api, filter_symbol)
dest.commands[name] = cmd
|
python
|
def import_command(dest, src, name, api=None, filter_symbol=None):
"""Import Command `name` and its dependencies from Registry `src`
to Registry `dest`
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Command to import
:param str api: Prefer to import Types with api name `api`, or None to
import Types with no api name
:param filter_symbol: Optional filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
"""
if not filter_symbol:
filter_symbol = _default_filter_symbol
cmd = src.commands[name]
for x in cmd.required_types:
if not filter_symbol('type', x):
continue
import_type(dest, src, x, api, filter_symbol)
dest.commands[name] = cmd
|
[
"def",
"import_command",
"(",
"dest",
",",
"src",
",",
"name",
",",
"api",
"=",
"None",
",",
"filter_symbol",
"=",
"None",
")",
":",
"if",
"not",
"filter_symbol",
":",
"filter_symbol",
"=",
"_default_filter_symbol",
"cmd",
"=",
"src",
".",
"commands",
"[",
"name",
"]",
"for",
"x",
"in",
"cmd",
".",
"required_types",
":",
"if",
"not",
"filter_symbol",
"(",
"'type'",
",",
"x",
")",
":",
"continue",
"import_type",
"(",
"dest",
",",
"src",
",",
"x",
",",
"api",
",",
"filter_symbol",
")",
"dest",
".",
"commands",
"[",
"name",
"]",
"=",
"cmd"
] |
Import Command `name` and its dependencies from Registry `src`
to Registry `dest`
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Command to import
:param str api: Prefer to import Types with api name `api`, or None to
import Types with no api name
:param filter_symbol: Optional filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
|
[
"Import",
"Command",
"name",
"and",
"its",
"dependencies",
"from",
"Registry",
"src",
"to",
"Registry",
"dest"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L817-L837
|
245,482
|
pyokagan/pyglreg
|
glreg.py
|
import_enum
|
def import_enum(dest, src, name):
"""Import Enum `name` from Registry `src` to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Enum to import
"""
dest.enums[name] = src.enums[name]
|
python
|
def import_enum(dest, src, name):
"""Import Enum `name` from Registry `src` to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Enum to import
"""
dest.enums[name] = src.enums[name]
|
[
"def",
"import_enum",
"(",
"dest",
",",
"src",
",",
"name",
")",
":",
"dest",
".",
"enums",
"[",
"name",
"]",
"=",
"src",
".",
"enums",
"[",
"name",
"]"
] |
Import Enum `name` from Registry `src` to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Enum to import
|
[
"Import",
"Enum",
"name",
"from",
"Registry",
"src",
"to",
"Registry",
"dest",
"."
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L840-L847
|
245,483
|
pyokagan/pyglreg
|
glreg.py
|
import_feature
|
def import_feature(dest, src, name, api=None, profile=None,
filter_symbol=None):
"""Imports Feature `name`, and all its dependencies, from
Registry `src` to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Feature to import
:param str api: Prefer to import dependencies with api name `api`,
or None to import dependencies with no API name.
:param str profile: Import dependencies with profile name
`profile`, or None to import all dependencies.
:param filter_symbol: Optional symbol filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
"""
if filter_symbol is None:
filter_symbol = _default_filter_symbol
ft = src.features[name] if isinstance(name, str) else name
# Gather symbols to remove from Feature
remove_symbols = set()
for x in src.get_removes(api, profile):
remove_symbols.update(x.as_symbols())
def my_filter_symbol(t, name):
return False if (t, name) in remove_symbols else filter_symbol(t, name)
for req in ft.get_requires(profile):
for x in req.types:
if not my_filter_symbol('type', x):
continue
import_type(dest, src, x, api, filter_symbol)
for x in req.enums:
if not my_filter_symbol('enum', x):
continue
import_enum(dest, src, x)
for x in req.commands:
if not my_filter_symbol('command', x):
continue
import_command(dest, src, x, api, filter_symbol)
dest.features[name] = ft
|
python
|
def import_feature(dest, src, name, api=None, profile=None,
filter_symbol=None):
"""Imports Feature `name`, and all its dependencies, from
Registry `src` to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Feature to import
:param str api: Prefer to import dependencies with api name `api`,
or None to import dependencies with no API name.
:param str profile: Import dependencies with profile name
`profile`, or None to import all dependencies.
:param filter_symbol: Optional symbol filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
"""
if filter_symbol is None:
filter_symbol = _default_filter_symbol
ft = src.features[name] if isinstance(name, str) else name
# Gather symbols to remove from Feature
remove_symbols = set()
for x in src.get_removes(api, profile):
remove_symbols.update(x.as_symbols())
def my_filter_symbol(t, name):
return False if (t, name) in remove_symbols else filter_symbol(t, name)
for req in ft.get_requires(profile):
for x in req.types:
if not my_filter_symbol('type', x):
continue
import_type(dest, src, x, api, filter_symbol)
for x in req.enums:
if not my_filter_symbol('enum', x):
continue
import_enum(dest, src, x)
for x in req.commands:
if not my_filter_symbol('command', x):
continue
import_command(dest, src, x, api, filter_symbol)
dest.features[name] = ft
|
[
"def",
"import_feature",
"(",
"dest",
",",
"src",
",",
"name",
",",
"api",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"filter_symbol",
"=",
"None",
")",
":",
"if",
"filter_symbol",
"is",
"None",
":",
"filter_symbol",
"=",
"_default_filter_symbol",
"ft",
"=",
"src",
".",
"features",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"name",
",",
"str",
")",
"else",
"name",
"# Gather symbols to remove from Feature",
"remove_symbols",
"=",
"set",
"(",
")",
"for",
"x",
"in",
"src",
".",
"get_removes",
"(",
"api",
",",
"profile",
")",
":",
"remove_symbols",
".",
"update",
"(",
"x",
".",
"as_symbols",
"(",
")",
")",
"def",
"my_filter_symbol",
"(",
"t",
",",
"name",
")",
":",
"return",
"False",
"if",
"(",
"t",
",",
"name",
")",
"in",
"remove_symbols",
"else",
"filter_symbol",
"(",
"t",
",",
"name",
")",
"for",
"req",
"in",
"ft",
".",
"get_requires",
"(",
"profile",
")",
":",
"for",
"x",
"in",
"req",
".",
"types",
":",
"if",
"not",
"my_filter_symbol",
"(",
"'type'",
",",
"x",
")",
":",
"continue",
"import_type",
"(",
"dest",
",",
"src",
",",
"x",
",",
"api",
",",
"filter_symbol",
")",
"for",
"x",
"in",
"req",
".",
"enums",
":",
"if",
"not",
"my_filter_symbol",
"(",
"'enum'",
",",
"x",
")",
":",
"continue",
"import_enum",
"(",
"dest",
",",
"src",
",",
"x",
")",
"for",
"x",
"in",
"req",
".",
"commands",
":",
"if",
"not",
"my_filter_symbol",
"(",
"'command'",
",",
"x",
")",
":",
"continue",
"import_command",
"(",
"dest",
",",
"src",
",",
"x",
",",
"api",
",",
"filter_symbol",
")",
"dest",
".",
"features",
"[",
"name",
"]",
"=",
"ft"
] |
Imports Feature `name`, and all its dependencies, from
Registry `src` to Registry `dest`.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Feature to import
:param str api: Prefer to import dependencies with api name `api`,
or None to import dependencies with no API name.
:param str profile: Import dependencies with profile name
`profile`, or None to import all dependencies.
:param filter_symbol: Optional symbol filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
|
[
"Imports",
"Feature",
"name",
"and",
"all",
"its",
"dependencies",
"from",
"Registry",
"src",
"to",
"Registry",
"dest",
"."
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L850-L890
|
245,484
|
pyokagan/pyglreg
|
glreg.py
|
import_extension
|
def import_extension(dest, src, name, api=None, profile=None,
filter_symbol=None):
"""Imports Extension `name`, and all its dependencies.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Extension to import
:param str api: Prefer to import types with API name `api`,
or None to prefer Types with no API name.
:type api: str
:param filter_symbol: Optional symbol filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
"""
if filter_symbol is None:
filter_symbol = _default_filter_symbol
ext = src.extensions[name] if isinstance(name, str) else name
for req in ext.get_requires(api, profile):
for x in req.types:
if not filter_symbol('type', x):
continue
import_type(dest, src, x, api, filter_symbol)
for x in req.enums:
if not filter_symbol('enum', x):
continue
import_enum(dest, src, x)
for x in req.commands:
if not filter_symbol('command', x):
continue
import_command(dest, src, x, api, filter_symbol)
dest.extensions[name] = ext
|
python
|
def import_extension(dest, src, name, api=None, profile=None,
filter_symbol=None):
"""Imports Extension `name`, and all its dependencies.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Extension to import
:param str api: Prefer to import types with API name `api`,
or None to prefer Types with no API name.
:type api: str
:param filter_symbol: Optional symbol filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
"""
if filter_symbol is None:
filter_symbol = _default_filter_symbol
ext = src.extensions[name] if isinstance(name, str) else name
for req in ext.get_requires(api, profile):
for x in req.types:
if not filter_symbol('type', x):
continue
import_type(dest, src, x, api, filter_symbol)
for x in req.enums:
if not filter_symbol('enum', x):
continue
import_enum(dest, src, x)
for x in req.commands:
if not filter_symbol('command', x):
continue
import_command(dest, src, x, api, filter_symbol)
dest.extensions[name] = ext
|
[
"def",
"import_extension",
"(",
"dest",
",",
"src",
",",
"name",
",",
"api",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"filter_symbol",
"=",
"None",
")",
":",
"if",
"filter_symbol",
"is",
"None",
":",
"filter_symbol",
"=",
"_default_filter_symbol",
"ext",
"=",
"src",
".",
"extensions",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"name",
",",
"str",
")",
"else",
"name",
"for",
"req",
"in",
"ext",
".",
"get_requires",
"(",
"api",
",",
"profile",
")",
":",
"for",
"x",
"in",
"req",
".",
"types",
":",
"if",
"not",
"filter_symbol",
"(",
"'type'",
",",
"x",
")",
":",
"continue",
"import_type",
"(",
"dest",
",",
"src",
",",
"x",
",",
"api",
",",
"filter_symbol",
")",
"for",
"x",
"in",
"req",
".",
"enums",
":",
"if",
"not",
"filter_symbol",
"(",
"'enum'",
",",
"x",
")",
":",
"continue",
"import_enum",
"(",
"dest",
",",
"src",
",",
"x",
")",
"for",
"x",
"in",
"req",
".",
"commands",
":",
"if",
"not",
"filter_symbol",
"(",
"'command'",
",",
"x",
")",
":",
"continue",
"import_command",
"(",
"dest",
",",
"src",
",",
"x",
",",
"api",
",",
"filter_symbol",
")",
"dest",
".",
"extensions",
"[",
"name",
"]",
"=",
"ext"
] |
Imports Extension `name`, and all its dependencies.
:param Registry dest: Destination Registry
:param Registry src: Source Registry
:param str name: Name of Extension to import
:param str api: Prefer to import types with API name `api`,
or None to prefer Types with no API name.
:type api: str
:param filter_symbol: Optional symbol filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
|
[
"Imports",
"Extension",
"name",
"and",
"all",
"its",
"dependencies",
"."
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L893-L923
|
245,485
|
pyokagan/pyglreg
|
glreg.py
|
import_registry
|
def import_registry(dest, src, api=None, profile=None, support=None,
filter_symbol=None):
"""Imports all features and extensions and all their dependencies.
:param Registry dest: Destination API
:param Registry src: Source Registry
:param str api: Only import Features with API name `api`, or None
to import all features.
:param str profile: Only import Features with profile name `profile`,
or None to import all features.
:param str support: Only import Extensions with this extension support
string, or None to import all extensions.
:param filter_symbol: Optional symbol filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
"""
if filter_symbol is None:
filter_symbol = _default_filter_symbol
for x in src.get_features(api):
import_feature(dest, src, x.name, api, profile, filter_symbol)
for x in src.get_extensions(support):
import_extension(dest, src, x.name, api, profile, filter_symbol)
|
python
|
def import_registry(dest, src, api=None, profile=None, support=None,
filter_symbol=None):
"""Imports all features and extensions and all their dependencies.
:param Registry dest: Destination API
:param Registry src: Source Registry
:param str api: Only import Features with API name `api`, or None
to import all features.
:param str profile: Only import Features with profile name `profile`,
or None to import all features.
:param str support: Only import Extensions with this extension support
string, or None to import all extensions.
:param filter_symbol: Optional symbol filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
"""
if filter_symbol is None:
filter_symbol = _default_filter_symbol
for x in src.get_features(api):
import_feature(dest, src, x.name, api, profile, filter_symbol)
for x in src.get_extensions(support):
import_extension(dest, src, x.name, api, profile, filter_symbol)
|
[
"def",
"import_registry",
"(",
"dest",
",",
"src",
",",
"api",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"support",
"=",
"None",
",",
"filter_symbol",
"=",
"None",
")",
":",
"if",
"filter_symbol",
"is",
"None",
":",
"filter_symbol",
"=",
"_default_filter_symbol",
"for",
"x",
"in",
"src",
".",
"get_features",
"(",
"api",
")",
":",
"import_feature",
"(",
"dest",
",",
"src",
",",
"x",
".",
"name",
",",
"api",
",",
"profile",
",",
"filter_symbol",
")",
"for",
"x",
"in",
"src",
".",
"get_extensions",
"(",
"support",
")",
":",
"import_extension",
"(",
"dest",
",",
"src",
",",
"x",
".",
"name",
",",
"api",
",",
"profile",
",",
"filter_symbol",
")"
] |
Imports all features and extensions and all their dependencies.
:param Registry dest: Destination API
:param Registry src: Source Registry
:param str api: Only import Features with API name `api`, or None
to import all features.
:param str profile: Only import Features with profile name `profile`,
or None to import all features.
:param str support: Only import Extensions with this extension support
string, or None to import all extensions.
:param filter_symbol: Optional symbol filter callable
:type filter_symbol: Callable with signature
``(symbol_type:str, symbol_name:str) -> bool``
|
[
"Imports",
"all",
"features",
"and",
"extensions",
"and",
"all",
"their",
"dependencies",
"."
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L926-L947
|
245,486
|
pyokagan/pyglreg
|
glreg.py
|
extension_sort_key
|
def extension_sort_key(extension):
"""Returns the sorting key for an extension.
The sorting key can be used to sort a list of extensions
into the order that is used in the Khronos C OpenGL headers.
:param Extension extension: Extension to produce sort key for
:returns: A sorting key
"""
name = extension.name
category = name.split('_', 2)[1]
return (0, name) if category in ('ARB', 'KHR', 'OES') else (1, name)
|
python
|
def extension_sort_key(extension):
"""Returns the sorting key for an extension.
The sorting key can be used to sort a list of extensions
into the order that is used in the Khronos C OpenGL headers.
:param Extension extension: Extension to produce sort key for
:returns: A sorting key
"""
name = extension.name
category = name.split('_', 2)[1]
return (0, name) if category in ('ARB', 'KHR', 'OES') else (1, name)
|
[
"def",
"extension_sort_key",
"(",
"extension",
")",
":",
"name",
"=",
"extension",
".",
"name",
"category",
"=",
"name",
".",
"split",
"(",
"'_'",
",",
"2",
")",
"[",
"1",
"]",
"return",
"(",
"0",
",",
"name",
")",
"if",
"category",
"in",
"(",
"'ARB'",
",",
"'KHR'",
",",
"'OES'",
")",
"else",
"(",
"1",
",",
"name",
")"
] |
Returns the sorting key for an extension.
The sorting key can be used to sort a list of extensions
into the order that is used in the Khronos C OpenGL headers.
:param Extension extension: Extension to produce sort key for
:returns: A sorting key
|
[
"Returns",
"the",
"sorting",
"key",
"for",
"an",
"extension",
"."
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L950-L960
|
245,487
|
pyokagan/pyglreg
|
glreg.py
|
group_apis
|
def group_apis(reg, features=None, extensions=None, api=None, profile=None,
support=None):
"""Groups Types, Enums, Commands with their respective Features, Extensions
Similar to :py:func:`import_registry`, but generates a new Registry object
for every feature or extension.
:param Registry reg: Input registry
:param features: Feature names to import, or None to import all.
:type features: Iterable of strs
:param extensions: Extension names to import, or None to import all.
:type extensions: Iterable of strs
:param str profile: Import features which belong in `profile`, or None
to import all.
:param str api: Import features which belong in `api`, or None to
import all.
:param str support: Import extensions which belong in this extension
support string, or None to import all.
:returns: list of :py:class:`Registry` objects
"""
features = (reg.get_features(api) if features is None
else [reg.features[x] for x in features])
if extensions is None:
extensions = sorted(reg.get_extensions(support),
key=extension_sort_key)
else:
extensions = [reg.extensions[x] for x in extensions]
output_symbols = set()
def filter_symbol(type, name):
k = (type, name)
if k in output_symbols:
return False
else:
output_symbols.add(k)
return True
out_apis = []
for x in features:
out = Registry(x.name)
import_feature(out, reg, x.name, api, profile, filter_symbol)
out_apis.append(out)
for x in extensions:
out = Registry(x.name)
import_extension(out, reg, x.name, api, profile, filter_symbol)
out_apis.append(out)
return out_apis
|
python
|
def group_apis(reg, features=None, extensions=None, api=None, profile=None,
support=None):
"""Groups Types, Enums, Commands with their respective Features, Extensions
Similar to :py:func:`import_registry`, but generates a new Registry object
for every feature or extension.
:param Registry reg: Input registry
:param features: Feature names to import, or None to import all.
:type features: Iterable of strs
:param extensions: Extension names to import, or None to import all.
:type extensions: Iterable of strs
:param str profile: Import features which belong in `profile`, or None
to import all.
:param str api: Import features which belong in `api`, or None to
import all.
:param str support: Import extensions which belong in this extension
support string, or None to import all.
:returns: list of :py:class:`Registry` objects
"""
features = (reg.get_features(api) if features is None
else [reg.features[x] for x in features])
if extensions is None:
extensions = sorted(reg.get_extensions(support),
key=extension_sort_key)
else:
extensions = [reg.extensions[x] for x in extensions]
output_symbols = set()
def filter_symbol(type, name):
k = (type, name)
if k in output_symbols:
return False
else:
output_symbols.add(k)
return True
out_apis = []
for x in features:
out = Registry(x.name)
import_feature(out, reg, x.name, api, profile, filter_symbol)
out_apis.append(out)
for x in extensions:
out = Registry(x.name)
import_extension(out, reg, x.name, api, profile, filter_symbol)
out_apis.append(out)
return out_apis
|
[
"def",
"group_apis",
"(",
"reg",
",",
"features",
"=",
"None",
",",
"extensions",
"=",
"None",
",",
"api",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"support",
"=",
"None",
")",
":",
"features",
"=",
"(",
"reg",
".",
"get_features",
"(",
"api",
")",
"if",
"features",
"is",
"None",
"else",
"[",
"reg",
".",
"features",
"[",
"x",
"]",
"for",
"x",
"in",
"features",
"]",
")",
"if",
"extensions",
"is",
"None",
":",
"extensions",
"=",
"sorted",
"(",
"reg",
".",
"get_extensions",
"(",
"support",
")",
",",
"key",
"=",
"extension_sort_key",
")",
"else",
":",
"extensions",
"=",
"[",
"reg",
".",
"extensions",
"[",
"x",
"]",
"for",
"x",
"in",
"extensions",
"]",
"output_symbols",
"=",
"set",
"(",
")",
"def",
"filter_symbol",
"(",
"type",
",",
"name",
")",
":",
"k",
"=",
"(",
"type",
",",
"name",
")",
"if",
"k",
"in",
"output_symbols",
":",
"return",
"False",
"else",
":",
"output_symbols",
".",
"add",
"(",
"k",
")",
"return",
"True",
"out_apis",
"=",
"[",
"]",
"for",
"x",
"in",
"features",
":",
"out",
"=",
"Registry",
"(",
"x",
".",
"name",
")",
"import_feature",
"(",
"out",
",",
"reg",
",",
"x",
".",
"name",
",",
"api",
",",
"profile",
",",
"filter_symbol",
")",
"out_apis",
".",
"append",
"(",
"out",
")",
"for",
"x",
"in",
"extensions",
":",
"out",
"=",
"Registry",
"(",
"x",
".",
"name",
")",
"import_extension",
"(",
"out",
",",
"reg",
",",
"x",
".",
"name",
",",
"api",
",",
"profile",
",",
"filter_symbol",
")",
"out_apis",
".",
"append",
"(",
"out",
")",
"return",
"out_apis"
] |
Groups Types, Enums, Commands with their respective Features, Extensions
Similar to :py:func:`import_registry`, but generates a new Registry object
for every feature or extension.
:param Registry reg: Input registry
:param features: Feature names to import, or None to import all.
:type features: Iterable of strs
:param extensions: Extension names to import, or None to import all.
:type extensions: Iterable of strs
:param str profile: Import features which belong in `profile`, or None
to import all.
:param str api: Import features which belong in `api`, or None to
import all.
:param str support: Import extensions which belong in this extension
support string, or None to import all.
:returns: list of :py:class:`Registry` objects
|
[
"Groups",
"Types",
"Enums",
"Commands",
"with",
"their",
"respective",
"Features",
"Extensions"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L963-L1009
|
245,488
|
pyokagan/pyglreg
|
glreg.py
|
main
|
def main(args=None, prog=None):
"""Generates a C header file"""
args = args if args is not None else sys.argv[1:]
prog = prog if prog is not None else sys.argv[0]
# Prevent broken pipe exception from being raised.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
stdin = sys.stdin.buffer if hasattr(sys.stdin, 'buffer') else sys.stdin
p = argparse.ArgumentParser(prog=prog)
p.add_argument('-o', '--output', metavar='PATH',
type=argparse.FileType('w'), default=sys.stdout,
help='Write output to PATH')
p.add_argument('--api', help='Match API', default=None)
p.add_argument('--profile', help='Match profile', default=None)
p.add_argument('--support', default=None,
help='Match extension support string')
g = p.add_mutually_exclusive_group()
g.add_argument('--list-apis', action='store_true', dest='list_apis',
help='List apis in registry', default=False)
g.add_argument('--list-profiles', action='store_true', default=False,
dest='list_profiles', help='List profiles in registry')
g.add_argument('--list-supports', action='store_true',
dest='list_supports', default=False,
help='List extension support strings')
p.add_argument('registry', type=argparse.FileType('rb'), nargs='?',
default=stdin, help='Registry path')
args = p.parse_args(args)
o = args.output
try:
registry = load(args.registry)
if args.list_apis:
for x in sorted(registry.get_apis()):
print(x, file=o)
return 0
elif args.list_profiles:
for x in sorted(registry.get_profiles()):
print(x, file=o)
return 0
elif args.list_supports:
for x in sorted(registry.get_supports()):
print(x, file=o)
return 0
apis = group_apis(registry, None, None, args.api, args.profile,
args.support)
for api in apis:
print('#ifndef', api.name, file=o)
print('#define', api.name, file=o)
print(api.text, file=o)
print('#endif', file=o)
print('', file=o)
except:
e = sys.exc_info()[1]
print(prog, ': error: ', e, sep='', file=sys.stderr)
return 1
return 0
|
python
|
def main(args=None, prog=None):
"""Generates a C header file"""
args = args if args is not None else sys.argv[1:]
prog = prog if prog is not None else sys.argv[0]
# Prevent broken pipe exception from being raised.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
stdin = sys.stdin.buffer if hasattr(sys.stdin, 'buffer') else sys.stdin
p = argparse.ArgumentParser(prog=prog)
p.add_argument('-o', '--output', metavar='PATH',
type=argparse.FileType('w'), default=sys.stdout,
help='Write output to PATH')
p.add_argument('--api', help='Match API', default=None)
p.add_argument('--profile', help='Match profile', default=None)
p.add_argument('--support', default=None,
help='Match extension support string')
g = p.add_mutually_exclusive_group()
g.add_argument('--list-apis', action='store_true', dest='list_apis',
help='List apis in registry', default=False)
g.add_argument('--list-profiles', action='store_true', default=False,
dest='list_profiles', help='List profiles in registry')
g.add_argument('--list-supports', action='store_true',
dest='list_supports', default=False,
help='List extension support strings')
p.add_argument('registry', type=argparse.FileType('rb'), nargs='?',
default=stdin, help='Registry path')
args = p.parse_args(args)
o = args.output
try:
registry = load(args.registry)
if args.list_apis:
for x in sorted(registry.get_apis()):
print(x, file=o)
return 0
elif args.list_profiles:
for x in sorted(registry.get_profiles()):
print(x, file=o)
return 0
elif args.list_supports:
for x in sorted(registry.get_supports()):
print(x, file=o)
return 0
apis = group_apis(registry, None, None, args.api, args.profile,
args.support)
for api in apis:
print('#ifndef', api.name, file=o)
print('#define', api.name, file=o)
print(api.text, file=o)
print('#endif', file=o)
print('', file=o)
except:
e = sys.exc_info()[1]
print(prog, ': error: ', e, sep='', file=sys.stderr)
return 1
return 0
|
[
"def",
"main",
"(",
"args",
"=",
"None",
",",
"prog",
"=",
"None",
")",
":",
"args",
"=",
"args",
"if",
"args",
"is",
"not",
"None",
"else",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"prog",
"=",
"prog",
"if",
"prog",
"is",
"not",
"None",
"else",
"sys",
".",
"argv",
"[",
"0",
"]",
"# Prevent broken pipe exception from being raised.",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGPIPE",
",",
"signal",
".",
"SIG_DFL",
")",
"stdin",
"=",
"sys",
".",
"stdin",
".",
"buffer",
"if",
"hasattr",
"(",
"sys",
".",
"stdin",
",",
"'buffer'",
")",
"else",
"sys",
".",
"stdin",
"p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"prog",
")",
"p",
".",
"add_argument",
"(",
"'-o'",
",",
"'--output'",
",",
"metavar",
"=",
"'PATH'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
"'w'",
")",
",",
"default",
"=",
"sys",
".",
"stdout",
",",
"help",
"=",
"'Write output to PATH'",
")",
"p",
".",
"add_argument",
"(",
"'--api'",
",",
"help",
"=",
"'Match API'",
",",
"default",
"=",
"None",
")",
"p",
".",
"add_argument",
"(",
"'--profile'",
",",
"help",
"=",
"'Match profile'",
",",
"default",
"=",
"None",
")",
"p",
".",
"add_argument",
"(",
"'--support'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Match extension support string'",
")",
"g",
"=",
"p",
".",
"add_mutually_exclusive_group",
"(",
")",
"g",
".",
"add_argument",
"(",
"'--list-apis'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'list_apis'",
",",
"help",
"=",
"'List apis in registry'",
",",
"default",
"=",
"False",
")",
"g",
".",
"add_argument",
"(",
"'--list-profiles'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"dest",
"=",
"'list_profiles'",
",",
"help",
"=",
"'List profiles in registry'",
")",
"g",
".",
"add_argument",
"(",
"'--list-supports'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'list_supports'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'List extension support strings'",
")",
"p",
".",
"add_argument",
"(",
"'registry'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
"'rb'",
")",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"stdin",
",",
"help",
"=",
"'Registry path'",
")",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"o",
"=",
"args",
".",
"output",
"try",
":",
"registry",
"=",
"load",
"(",
"args",
".",
"registry",
")",
"if",
"args",
".",
"list_apis",
":",
"for",
"x",
"in",
"sorted",
"(",
"registry",
".",
"get_apis",
"(",
")",
")",
":",
"print",
"(",
"x",
",",
"file",
"=",
"o",
")",
"return",
"0",
"elif",
"args",
".",
"list_profiles",
":",
"for",
"x",
"in",
"sorted",
"(",
"registry",
".",
"get_profiles",
"(",
")",
")",
":",
"print",
"(",
"x",
",",
"file",
"=",
"o",
")",
"return",
"0",
"elif",
"args",
".",
"list_supports",
":",
"for",
"x",
"in",
"sorted",
"(",
"registry",
".",
"get_supports",
"(",
")",
")",
":",
"print",
"(",
"x",
",",
"file",
"=",
"o",
")",
"return",
"0",
"apis",
"=",
"group_apis",
"(",
"registry",
",",
"None",
",",
"None",
",",
"args",
".",
"api",
",",
"args",
".",
"profile",
",",
"args",
".",
"support",
")",
"for",
"api",
"in",
"apis",
":",
"print",
"(",
"'#ifndef'",
",",
"api",
".",
"name",
",",
"file",
"=",
"o",
")",
"print",
"(",
"'#define'",
",",
"api",
".",
"name",
",",
"file",
"=",
"o",
")",
"print",
"(",
"api",
".",
"text",
",",
"file",
"=",
"o",
")",
"print",
"(",
"'#endif'",
",",
"file",
"=",
"o",
")",
"print",
"(",
"''",
",",
"file",
"=",
"o",
")",
"except",
":",
"e",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"print",
"(",
"prog",
",",
"': error: '",
",",
"e",
",",
"sep",
"=",
"''",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"return",
"1",
"return",
"0"
] |
Generates a C header file
|
[
"Generates",
"a",
"C",
"header",
"file"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L1012-L1065
|
245,489
|
pyokagan/pyglreg
|
glreg.py
|
Command.required_types
|
def required_types(self):
"""Set of names of types which the Command depends on.
"""
required_types = set(x.type for x in self.params)
required_types.add(self.type)
required_types.discard(None)
return required_types
|
python
|
def required_types(self):
"""Set of names of types which the Command depends on.
"""
required_types = set(x.type for x in self.params)
required_types.add(self.type)
required_types.discard(None)
return required_types
|
[
"def",
"required_types",
"(",
"self",
")",
":",
"required_types",
"=",
"set",
"(",
"x",
".",
"type",
"for",
"x",
"in",
"self",
".",
"params",
")",
"required_types",
".",
"add",
"(",
"self",
".",
"type",
")",
"required_types",
".",
"discard",
"(",
"None",
")",
"return",
"required_types"
] |
Set of names of types which the Command depends on.
|
[
"Set",
"of",
"names",
"of",
"types",
"which",
"the",
"Command",
"depends",
"on",
"."
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L202-L208
|
245,490
|
pyokagan/pyglreg
|
glreg.py
|
Command.proto_text
|
def proto_text(self):
"""Formatted Command identifier.
Equivalent to ``self.proto_template.format(type=self.type,
name=self.name)``.
"""
return self.proto_template.format(type=self.type, name=self.name)
|
python
|
def proto_text(self):
"""Formatted Command identifier.
Equivalent to ``self.proto_template.format(type=self.type,
name=self.name)``.
"""
return self.proto_template.format(type=self.type, name=self.name)
|
[
"def",
"proto_text",
"(",
"self",
")",
":",
"return",
"self",
".",
"proto_template",
".",
"format",
"(",
"type",
"=",
"self",
".",
"type",
",",
"name",
"=",
"self",
".",
"name",
")"
] |
Formatted Command identifier.
Equivalent to ``self.proto_template.format(type=self.type,
name=self.name)``.
|
[
"Formatted",
"Command",
"identifier",
"."
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L211-L217
|
245,491
|
pyokagan/pyglreg
|
glreg.py
|
Command.text
|
def text(self):
"""Formatted Command declaration.
This is the C declaration for the command.
"""
params = ', '.join(x.text for x in self.params)
return '{0} ({1})'.format(self.proto_text, params)
|
python
|
def text(self):
"""Formatted Command declaration.
This is the C declaration for the command.
"""
params = ', '.join(x.text for x in self.params)
return '{0} ({1})'.format(self.proto_text, params)
|
[
"def",
"text",
"(",
"self",
")",
":",
"params",
"=",
"', '",
".",
"join",
"(",
"x",
".",
"text",
"for",
"x",
"in",
"self",
".",
"params",
")",
"return",
"'{0} ({1})'",
".",
"format",
"(",
"self",
".",
"proto_text",
",",
"params",
")"
] |
Formatted Command declaration.
This is the C declaration for the command.
|
[
"Formatted",
"Command",
"declaration",
"."
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L220-L226
|
245,492
|
pyokagan/pyglreg
|
glreg.py
|
Param.text
|
def text(self):
"""Formatted param definition
Equivalent to ``self.template.format(name=self.name, type=self.type)``.
"""
return self.template.format(name=self.name, type=self.type)
|
python
|
def text(self):
"""Formatted param definition
Equivalent to ``self.template.format(name=self.name, type=self.type)``.
"""
return self.template.format(name=self.name, type=self.type)
|
[
"def",
"text",
"(",
"self",
")",
":",
"return",
"self",
".",
"template",
".",
"format",
"(",
"name",
"=",
"self",
".",
"name",
",",
"type",
"=",
"self",
".",
"type",
")"
] |
Formatted param definition
Equivalent to ``self.template.format(name=self.name, type=self.type)``.
|
[
"Formatted",
"param",
"definition"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L243-L248
|
245,493
|
pyokagan/pyglreg
|
glreg.py
|
Require.as_symbols
|
def as_symbols(self):
"""Set of symbols required by this Require
:return: set of ``(symbol type, symbol name)`` tuples
"""
out = set()
for name in self.types:
out.add(('type', name))
for name in self.enums:
out.add(('enum', name))
for name in self.commands:
out.add(('command', name))
return out
|
python
|
def as_symbols(self):
"""Set of symbols required by this Require
:return: set of ``(symbol type, symbol name)`` tuples
"""
out = set()
for name in self.types:
out.add(('type', name))
for name in self.enums:
out.add(('enum', name))
for name in self.commands:
out.add(('command', name))
return out
|
[
"def",
"as_symbols",
"(",
"self",
")",
":",
"out",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"self",
".",
"types",
":",
"out",
".",
"add",
"(",
"(",
"'type'",
",",
"name",
")",
")",
"for",
"name",
"in",
"self",
".",
"enums",
":",
"out",
".",
"add",
"(",
"(",
"'enum'",
",",
"name",
")",
")",
"for",
"name",
"in",
"self",
".",
"commands",
":",
"out",
".",
"add",
"(",
"(",
"'command'",
",",
"name",
")",
")",
"return",
"out"
] |
Set of symbols required by this Require
:return: set of ``(symbol type, symbol name)`` tuples
|
[
"Set",
"of",
"symbols",
"required",
"by",
"this",
"Require"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L274-L286
|
245,494
|
pyokagan/pyglreg
|
glreg.py
|
Feature.get_profiles
|
def get_profiles(self):
"""Returns set of profile names referenced in this Feature
:returns: set of profile names
"""
out = set(x.profile for x in self.requires if x.profile)
out.update(x.profile for x in self.removes if x.profile)
return out
|
python
|
def get_profiles(self):
"""Returns set of profile names referenced in this Feature
:returns: set of profile names
"""
out = set(x.profile for x in self.requires if x.profile)
out.update(x.profile for x in self.removes if x.profile)
return out
|
[
"def",
"get_profiles",
"(",
"self",
")",
":",
"out",
"=",
"set",
"(",
"x",
".",
"profile",
"for",
"x",
"in",
"self",
".",
"requires",
"if",
"x",
".",
"profile",
")",
"out",
".",
"update",
"(",
"x",
".",
"profile",
"for",
"x",
"in",
"self",
".",
"removes",
"if",
"x",
".",
"profile",
")",
"return",
"out"
] |
Returns set of profile names referenced in this Feature
:returns: set of profile names
|
[
"Returns",
"set",
"of",
"profile",
"names",
"referenced",
"in",
"this",
"Feature"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L355-L362
|
245,495
|
pyokagan/pyglreg
|
glreg.py
|
Feature.get_requires
|
def get_requires(self, profile=None):
"""Get filtered list of Require objects in this Feature
:param str profile: Return Require objects with this profile or None
to return all Require objects.
:return: list of Require objects
"""
out = []
for req in self.requires:
# Filter Require by profile
if ((req.profile and not profile) or
(req.profile and profile and req.profile != profile)):
continue
out.append(req)
return out
|
python
|
def get_requires(self, profile=None):
"""Get filtered list of Require objects in this Feature
:param str profile: Return Require objects with this profile or None
to return all Require objects.
:return: list of Require objects
"""
out = []
for req in self.requires:
# Filter Require by profile
if ((req.profile and not profile) or
(req.profile and profile and req.profile != profile)):
continue
out.append(req)
return out
|
[
"def",
"get_requires",
"(",
"self",
",",
"profile",
"=",
"None",
")",
":",
"out",
"=",
"[",
"]",
"for",
"req",
"in",
"self",
".",
"requires",
":",
"# Filter Require by profile",
"if",
"(",
"(",
"req",
".",
"profile",
"and",
"not",
"profile",
")",
"or",
"(",
"req",
".",
"profile",
"and",
"profile",
"and",
"req",
".",
"profile",
"!=",
"profile",
")",
")",
":",
"continue",
"out",
".",
"append",
"(",
"req",
")",
"return",
"out"
] |
Get filtered list of Require objects in this Feature
:param str profile: Return Require objects with this profile or None
to return all Require objects.
:return: list of Require objects
|
[
"Get",
"filtered",
"list",
"of",
"Require",
"objects",
"in",
"this",
"Feature"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L364-L378
|
245,496
|
pyokagan/pyglreg
|
glreg.py
|
Feature.get_removes
|
def get_removes(self, profile=None):
"""Get filtered list of Remove objects in this Feature
:param str profile: Return Remove objects with this profile or None
to return all Remove objects.
:return: list of Remove objects
"""
out = []
for rem in self.removes:
# Filter Remove by profile
if ((rem.profile and not profile) or
(rem.profile and profile and rem.profile != profile)):
continue
out.append(rem)
return out
|
python
|
def get_removes(self, profile=None):
"""Get filtered list of Remove objects in this Feature
:param str profile: Return Remove objects with this profile or None
to return all Remove objects.
:return: list of Remove objects
"""
out = []
for rem in self.removes:
# Filter Remove by profile
if ((rem.profile and not profile) or
(rem.profile and profile and rem.profile != profile)):
continue
out.append(rem)
return out
|
[
"def",
"get_removes",
"(",
"self",
",",
"profile",
"=",
"None",
")",
":",
"out",
"=",
"[",
"]",
"for",
"rem",
"in",
"self",
".",
"removes",
":",
"# Filter Remove by profile",
"if",
"(",
"(",
"rem",
".",
"profile",
"and",
"not",
"profile",
")",
"or",
"(",
"rem",
".",
"profile",
"and",
"profile",
"and",
"rem",
".",
"profile",
"!=",
"profile",
")",
")",
":",
"continue",
"out",
".",
"append",
"(",
"rem",
")",
"return",
"out"
] |
Get filtered list of Remove objects in this Feature
:param str profile: Return Remove objects with this profile or None
to return all Remove objects.
:return: list of Remove objects
|
[
"Get",
"filtered",
"list",
"of",
"Remove",
"objects",
"in",
"this",
"Feature"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L380-L394
|
245,497
|
pyokagan/pyglreg
|
glreg.py
|
Extension.get_apis
|
def get_apis(self):
"""Returns set of api names referenced in this Extension
:return: set of api name strings
"""
out = set()
out.update(x.api for x in self.requires if x.api)
return out
|
python
|
def get_apis(self):
"""Returns set of api names referenced in this Extension
:return: set of api name strings
"""
out = set()
out.update(x.api for x in self.requires if x.api)
return out
|
[
"def",
"get_apis",
"(",
"self",
")",
":",
"out",
"=",
"set",
"(",
")",
"out",
".",
"update",
"(",
"x",
".",
"api",
"for",
"x",
"in",
"self",
".",
"requires",
"if",
"x",
".",
"api",
")",
"return",
"out"
] |
Returns set of api names referenced in this Extension
:return: set of api name strings
|
[
"Returns",
"set",
"of",
"api",
"names",
"referenced",
"in",
"this",
"Extension"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L416-L423
|
245,498
|
pyokagan/pyglreg
|
glreg.py
|
Extension.get_profiles
|
def get_profiles(self):
"""Returns set of profile names referenced in this Extension
:return: set of profile name strings
"""
return set(x.profile for x in self.requires if x.profile)
|
python
|
def get_profiles(self):
"""Returns set of profile names referenced in this Extension
:return: set of profile name strings
"""
return set(x.profile for x in self.requires if x.profile)
|
[
"def",
"get_profiles",
"(",
"self",
")",
":",
"return",
"set",
"(",
"x",
".",
"profile",
"for",
"x",
"in",
"self",
".",
"requires",
"if",
"x",
".",
"profile",
")"
] |
Returns set of profile names referenced in this Extension
:return: set of profile name strings
|
[
"Returns",
"set",
"of",
"profile",
"names",
"referenced",
"in",
"this",
"Extension"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L425-L430
|
245,499
|
pyokagan/pyglreg
|
glreg.py
|
Extension.get_requires
|
def get_requires(self, api=None, profile=None):
"""Return filtered list of Require objects in this Extension
:param str api: Return Require objects with this api name or None to
return all Require objects.
:param str profile: Return Require objects with this profile or None
to return all Require objects.
:return: list of Require objects
"""
out = []
for req in self.requires:
# Filter Remove by API
if (req.api and not api) or (req.api and api and req.api != api):
continue
# Filter Remove by profile
if ((req.profile and not profile) or
(req.profile and profile and req.profile != profile)):
continue
out.append(req)
return out
|
python
|
def get_requires(self, api=None, profile=None):
"""Return filtered list of Require objects in this Extension
:param str api: Return Require objects with this api name or None to
return all Require objects.
:param str profile: Return Require objects with this profile or None
to return all Require objects.
:return: list of Require objects
"""
out = []
for req in self.requires:
# Filter Remove by API
if (req.api and not api) or (req.api and api and req.api != api):
continue
# Filter Remove by profile
if ((req.profile and not profile) or
(req.profile and profile and req.profile != profile)):
continue
out.append(req)
return out
|
[
"def",
"get_requires",
"(",
"self",
",",
"api",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"out",
"=",
"[",
"]",
"for",
"req",
"in",
"self",
".",
"requires",
":",
"# Filter Remove by API",
"if",
"(",
"req",
".",
"api",
"and",
"not",
"api",
")",
"or",
"(",
"req",
".",
"api",
"and",
"api",
"and",
"req",
".",
"api",
"!=",
"api",
")",
":",
"continue",
"# Filter Remove by profile",
"if",
"(",
"(",
"req",
".",
"profile",
"and",
"not",
"profile",
")",
"or",
"(",
"req",
".",
"profile",
"and",
"profile",
"and",
"req",
".",
"profile",
"!=",
"profile",
")",
")",
":",
"continue",
"out",
".",
"append",
"(",
"req",
")",
"return",
"out"
] |
Return filtered list of Require objects in this Extension
:param str api: Return Require objects with this api name or None to
return all Require objects.
:param str profile: Return Require objects with this profile or None
to return all Require objects.
:return: list of Require objects
|
[
"Return",
"filtered",
"list",
"of",
"Require",
"objects",
"in",
"this",
"Extension"
] |
68fa5a6c6cee8667879840fbbcc7d30f52852915
|
https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L439-L458
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.