body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
|---|---|---|---|---|---|---|---|---|---|
c3ff15c222f177e2789c3d36f8f44f7d534c27672bb5d0c39f4ac8c747e1021d
|
@first_name.setter
def first_name(self, first_name):
'Sets the first_name of this UpdateCurrentUserInputObject.\n\n Account first name. # noqa: E501\n\n :param first_name: The first_name of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._first_name = first_name
|
Sets the first_name of this UpdateCurrentUserInputObject.
Account first name. # noqa: E501
:param first_name: The first_name of this UpdateCurrentUserInputObject. # noqa: E501
:type: str
|
TextMagic/models/update_current_user_input_object.py
|
first_name
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@first_name.setter
def first_name(self, first_name):
'Sets the first_name of this UpdateCurrentUserInputObject.\n\n Account first name. # noqa: E501\n\n :param first_name: The first_name of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._first_name = first_name
|
@first_name.setter
def first_name(self, first_name):
'Sets the first_name of this UpdateCurrentUserInputObject.\n\n Account first name. # noqa: E501\n\n :param first_name: The first_name of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._first_name = first_name<|docstring|>Sets the first_name of this UpdateCurrentUserInputObject.
Account first name. # noqa: E501
:param first_name: The first_name of this UpdateCurrentUserInputObject. # noqa: E501
:type: str<|endoftext|>
|
fa5d7821335251cbfdda9baf5c10d35d227c7b99bcd0a3814a929334d307657f
|
@property
def last_name(self):
'Gets the last_name of this UpdateCurrentUserInputObject. # noqa: E501\n\n Account last name. # noqa: E501\n\n :return: The last_name of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._last_name
|
Gets the last_name of this UpdateCurrentUserInputObject. # noqa: E501
Account last name. # noqa: E501
:return: The last_name of this UpdateCurrentUserInputObject. # noqa: E501
:rtype: str
|
TextMagic/models/update_current_user_input_object.py
|
last_name
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@property
def last_name(self):
'Gets the last_name of this UpdateCurrentUserInputObject. # noqa: E501\n\n Account last name. # noqa: E501\n\n :return: The last_name of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._last_name
|
@property
def last_name(self):
'Gets the last_name of this UpdateCurrentUserInputObject. # noqa: E501\n\n Account last name. # noqa: E501\n\n :return: The last_name of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._last_name<|docstring|>Gets the last_name of this UpdateCurrentUserInputObject. # noqa: E501
Account last name. # noqa: E501
:return: The last_name of this UpdateCurrentUserInputObject. # noqa: E501
:rtype: str<|endoftext|>
|
e4cfea487f73b837e492191241ab2935787b07a888d577907e64d4a1ecb20b3c
|
@last_name.setter
def last_name(self, last_name):
'Sets the last_name of this UpdateCurrentUserInputObject.\n\n Account last name. # noqa: E501\n\n :param last_name: The last_name of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._last_name = last_name
|
Sets the last_name of this UpdateCurrentUserInputObject.
Account last name. # noqa: E501
:param last_name: The last_name of this UpdateCurrentUserInputObject. # noqa: E501
:type: str
|
TextMagic/models/update_current_user_input_object.py
|
last_name
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@last_name.setter
def last_name(self, last_name):
'Sets the last_name of this UpdateCurrentUserInputObject.\n\n Account last name. # noqa: E501\n\n :param last_name: The last_name of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._last_name = last_name
|
@last_name.setter
def last_name(self, last_name):
'Sets the last_name of this UpdateCurrentUserInputObject.\n\n Account last name. # noqa: E501\n\n :param last_name: The last_name of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._last_name = last_name<|docstring|>Sets the last_name of this UpdateCurrentUserInputObject.
Account last name. # noqa: E501
:param last_name: The last_name of this UpdateCurrentUserInputObject. # noqa: E501
:type: str<|endoftext|>
|
53f672bf79912bd8f81b6d887a32ebd814564539fdd968d7e8821c641dd3c4d5
|
@property
def email(self):
'Gets the email of this UpdateCurrentUserInputObject. # noqa: E501\n\n\n :return: The email of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._email
|
Gets the email of this UpdateCurrentUserInputObject. # noqa: E501
:return: The email of this UpdateCurrentUserInputObject. # noqa: E501
:rtype: str
|
TextMagic/models/update_current_user_input_object.py
|
email
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@property
def email(self):
'Gets the email of this UpdateCurrentUserInputObject. # noqa: E501\n\n\n :return: The email of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._email
|
@property
def email(self):
'Gets the email of this UpdateCurrentUserInputObject. # noqa: E501\n\n\n :return: The email of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._email<|docstring|>Gets the email of this UpdateCurrentUserInputObject. # noqa: E501
:return: The email of this UpdateCurrentUserInputObject. # noqa: E501
:rtype: str<|endoftext|>
|
b4e503db19790603372d9de93db139868d24055d3ee935481672c32cacbb0346
|
@email.setter
def email(self, email):
'Sets the email of this UpdateCurrentUserInputObject.\n\n\n :param email: The email of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._email = email
|
Sets the email of this UpdateCurrentUserInputObject.
:param email: The email of this UpdateCurrentUserInputObject. # noqa: E501
:type: str
|
TextMagic/models/update_current_user_input_object.py
|
email
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@email.setter
def email(self, email):
'Sets the email of this UpdateCurrentUserInputObject.\n\n\n :param email: The email of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._email = email
|
@email.setter
def email(self, email):
'Sets the email of this UpdateCurrentUserInputObject.\n\n\n :param email: The email of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._email = email<|docstring|>Sets the email of this UpdateCurrentUserInputObject.
:param email: The email of this UpdateCurrentUserInputObject. # noqa: E501
:type: str<|endoftext|>
|
03f105e380de15d23b3953dff5e2b059660026735792068369861e0e11758dec
|
@property
def phone(self):
'Gets the phone of this UpdateCurrentUserInputObject. # noqa: E501\n\n\n :return: The phone of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._phone
|
Gets the phone of this UpdateCurrentUserInputObject. # noqa: E501
:return: The phone of this UpdateCurrentUserInputObject. # noqa: E501
:rtype: str
|
TextMagic/models/update_current_user_input_object.py
|
phone
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@property
def phone(self):
'Gets the phone of this UpdateCurrentUserInputObject. # noqa: E501\n\n\n :return: The phone of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._phone
|
@property
def phone(self):
'Gets the phone of this UpdateCurrentUserInputObject. # noqa: E501\n\n\n :return: The phone of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._phone<|docstring|>Gets the phone of this UpdateCurrentUserInputObject. # noqa: E501
:return: The phone of this UpdateCurrentUserInputObject. # noqa: E501
:rtype: str<|endoftext|>
|
a49e553916971a8a68b0b6396b37b5f431a5f6b1542069a50d1317052279311f
|
@phone.setter
def phone(self, phone):
'Sets the phone of this UpdateCurrentUserInputObject.\n\n\n :param phone: The phone of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._phone = phone
|
Sets the phone of this UpdateCurrentUserInputObject.
:param phone: The phone of this UpdateCurrentUserInputObject. # noqa: E501
:type: str
|
TextMagic/models/update_current_user_input_object.py
|
phone
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@phone.setter
def phone(self, phone):
'Sets the phone of this UpdateCurrentUserInputObject.\n\n\n :param phone: The phone of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._phone = phone
|
@phone.setter
def phone(self, phone):
'Sets the phone of this UpdateCurrentUserInputObject.\n\n\n :param phone: The phone of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._phone = phone<|docstring|>Sets the phone of this UpdateCurrentUserInputObject.
:param phone: The phone of this UpdateCurrentUserInputObject. # noqa: E501
:type: str<|endoftext|>
|
f3c896c1b780c4464feb050e305f654dd7f37f00111d2c6db115d7de9371e850
|
@property
def company(self):
'Gets the company of this UpdateCurrentUserInputObject. # noqa: E501\n\n Account company name. # noqa: E501\n\n :return: The company of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._company
|
Gets the company of this UpdateCurrentUserInputObject. # noqa: E501
Account company name. # noqa: E501
:return: The company of this UpdateCurrentUserInputObject. # noqa: E501
:rtype: str
|
TextMagic/models/update_current_user_input_object.py
|
company
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@property
def company(self):
'Gets the company of this UpdateCurrentUserInputObject. # noqa: E501\n\n Account company name. # noqa: E501\n\n :return: The company of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._company
|
@property
def company(self):
'Gets the company of this UpdateCurrentUserInputObject. # noqa: E501\n\n Account company name. # noqa: E501\n\n :return: The company of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: str\n '
return self._company<|docstring|>Gets the company of this UpdateCurrentUserInputObject. # noqa: E501
Account company name. # noqa: E501
:return: The company of this UpdateCurrentUserInputObject. # noqa: E501
:rtype: str<|endoftext|>
|
294f3f12d6810fb04cacdde60110ad044150c6ab4efc930d27053e2876228530
|
@company.setter
def company(self, company):
'Sets the company of this UpdateCurrentUserInputObject.\n\n Account company name. # noqa: E501\n\n :param company: The company of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._company = company
|
Sets the company of this UpdateCurrentUserInputObject.
Account company name. # noqa: E501
:param company: The company of this UpdateCurrentUserInputObject. # noqa: E501
:type: str
|
TextMagic/models/update_current_user_input_object.py
|
company
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@company.setter
def company(self, company):
'Sets the company of this UpdateCurrentUserInputObject.\n\n Account company name. # noqa: E501\n\n :param company: The company of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._company = company
|
@company.setter
def company(self, company):
'Sets the company of this UpdateCurrentUserInputObject.\n\n Account company name. # noqa: E501\n\n :param company: The company of this UpdateCurrentUserInputObject. # noqa: E501\n :type: str\n '
self._company = company<|docstring|>Sets the company of this UpdateCurrentUserInputObject.
Account company name. # noqa: E501
:param company: The company of this UpdateCurrentUserInputObject. # noqa: E501
:type: str<|endoftext|>
|
ff86578cfeb97cdaa53487dc870cdfd5d8d8f4c4f509bd4f841c5dc152425577
|
@property
def timezone(self):
'Gets the timezone of this UpdateCurrentUserInputObject. # noqa: E501\n\n The timezome internal ID. See [Get timezones](https://docs.textmagic.com/#operation/getTimezones). # noqa: E501\n\n :return: The timezone of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: int\n '
return self._timezone
|
Gets the timezone of this UpdateCurrentUserInputObject. # noqa: E501
The timezome internal ID. See [Get timezones](https://docs.textmagic.com/#operation/getTimezones). # noqa: E501
:return: The timezone of this UpdateCurrentUserInputObject. # noqa: E501
:rtype: int
|
TextMagic/models/update_current_user_input_object.py
|
timezone
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@property
def timezone(self):
'Gets the timezone of this UpdateCurrentUserInputObject. # noqa: E501\n\n The timezome internal ID. See [Get timezones](https://docs.textmagic.com/#operation/getTimezones). # noqa: E501\n\n :return: The timezone of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: int\n '
return self._timezone
|
@property
def timezone(self):
'Gets the timezone of this UpdateCurrentUserInputObject. # noqa: E501\n\n The timezome internal ID. See [Get timezones](https://docs.textmagic.com/#operation/getTimezones). # noqa: E501\n\n :return: The timezone of this UpdateCurrentUserInputObject. # noqa: E501\n :rtype: int\n '
return self._timezone<|docstring|>Gets the timezone of this UpdateCurrentUserInputObject. # noqa: E501
The timezome internal ID. See [Get timezones](https://docs.textmagic.com/#operation/getTimezones). # noqa: E501
:return: The timezone of this UpdateCurrentUserInputObject. # noqa: E501
:rtype: int<|endoftext|>
|
2d1aedf0857c3307e0057cab89b6b3f297a746142981a9713b2fbe46cc218b96
|
@timezone.setter
def timezone(self, timezone):
'Sets the timezone of this UpdateCurrentUserInputObject.\n\n The timezome internal ID. See [Get timezones](https://docs.textmagic.com/#operation/getTimezones). # noqa: E501\n\n :param timezone: The timezone of this UpdateCurrentUserInputObject. # noqa: E501\n :type: int\n '
self._timezone = timezone
|
Sets the timezone of this UpdateCurrentUserInputObject.
The timezome internal ID. See [Get timezones](https://docs.textmagic.com/#operation/getTimezones). # noqa: E501
:param timezone: The timezone of this UpdateCurrentUserInputObject. # noqa: E501
:type: int
|
TextMagic/models/update_current_user_input_object.py
|
timezone
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
@timezone.setter
def timezone(self, timezone):
'Sets the timezone of this UpdateCurrentUserInputObject.\n\n The timezome internal ID. See [Get timezones](https://docs.textmagic.com/#operation/getTimezones). # noqa: E501\n\n :param timezone: The timezone of this UpdateCurrentUserInputObject. # noqa: E501\n :type: int\n '
self._timezone = timezone
|
@timezone.setter
def timezone(self, timezone):
'Sets the timezone of this UpdateCurrentUserInputObject.\n\n The timezome internal ID. See [Get timezones](https://docs.textmagic.com/#operation/getTimezones). # noqa: E501\n\n :param timezone: The timezone of this UpdateCurrentUserInputObject. # noqa: E501\n :type: int\n '
self._timezone = timezone<|docstring|>Sets the timezone of this UpdateCurrentUserInputObject.
The timezome internal ID. See [Get timezones](https://docs.textmagic.com/#operation/getTimezones). # noqa: E501
:param timezone: The timezone of this UpdateCurrentUserInputObject. # noqa: E501
:type: int<|endoftext|>
|
1cfc4f96c272da5c1e2dd9894c41e4347f95fa1deb428a67143aae25a356fcd5
|
def to_dict(self):
'Returns the model properties as a dict'
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
if issubclass(UpdateCurrentUserInputObject, dict):
for (key, value) in self.items():
result[key] = value
return result
|
Returns the model properties as a dict
|
TextMagic/models/update_current_user_input_object.py
|
to_dict
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
if issubclass(UpdateCurrentUserInputObject, dict):
for (key, value) in self.items():
result[key] = value
return result
|
def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
if issubclass(UpdateCurrentUserInputObject, dict):
for (key, value) in self.items():
result[key] = value
return result<|docstring|>Returns the model properties as a dict<|endoftext|>
|
cbb19eaa2fc8a113d9e32f924ef280a7e97563f8915f94f65dab438997af2e99
|
def to_str(self):
'Returns the string representation of the model'
return pprint.pformat(self.to_dict())
|
Returns the string representation of the model
|
TextMagic/models/update_current_user_input_object.py
|
to_str
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
def to_str(self):
return pprint.pformat(self.to_dict())
|
def to_str(self):
return pprint.pformat(self.to_dict())<|docstring|>Returns the string representation of the model<|endoftext|>
|
772243a2c2b3261a9b954d07aaf295e3c1242a579a495e2d6a5679c677861703
|
def __repr__(self):
'For `print` and `pprint`'
return self.to_str()
|
For `print` and `pprint`
|
TextMagic/models/update_current_user_input_object.py
|
__repr__
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
def __repr__(self):
return self.to_str()
|
def __repr__(self):
return self.to_str()<|docstring|>For `print` and `pprint`<|endoftext|>
|
3de45dfa1475fc979d8ce505a196851ff85c80f56536093739cf6c644bdd09a5
|
def __eq__(self, other):
'Returns true if both objects are equal'
if (not isinstance(other, UpdateCurrentUserInputObject)):
return False
return (self.__dict__ == other.__dict__)
|
Returns true if both objects are equal
|
TextMagic/models/update_current_user_input_object.py
|
__eq__
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
def __eq__(self, other):
if (not isinstance(other, UpdateCurrentUserInputObject)):
return False
return (self.__dict__ == other.__dict__)
|
def __eq__(self, other):
if (not isinstance(other, UpdateCurrentUserInputObject)):
return False
return (self.__dict__ == other.__dict__)<|docstring|>Returns true if both objects are equal<|endoftext|>
|
43dc6740163eb9fc1161d09cb2208a64c7ad0cc8d9c8637ac3264522d3ec7e42
|
def __ne__(self, other):
'Returns true if both objects are not equal'
return (not (self == other))
|
Returns true if both objects are not equal
|
TextMagic/models/update_current_user_input_object.py
|
__ne__
|
textmagic/textmagic-rest-python-v2
| 2
|
python
|
def __ne__(self, other):
return (not (self == other))
|
def __ne__(self, other):
return (not (self == other))<|docstring|>Returns true if both objects are not equal<|endoftext|>
|
65c98a236e54ec1ffc6909c8a8040dab2bfa7c10bcd1192f78de9f0cdc2ff9b6
|
def WaleMatPlot(tempo, sinal, salve=1, name='Sinal.png', real=1):
'Gera um gráfico em Matplotlib de linha feito para demonstração grafica de sinais\n Argumentos: \n Tempo: Um numpy array com os valores do tempo\n Sinal: Uma lista de numpy Array com os valores do sinal em relação ao tempo\n Salve: 1 para gravar em PNG, 0 para exibir em Pop Up\n Name: Nome do arquivo em caso de salvar png\n Retorno:\n Exibe um Grafico\n \n '
plt.figure(2)
plt.ylabel('Amplitude')
plt.xlabel('Time [s]')
for x in sinal:
if real:
X = [d.real for d in x]
Y = [y.imag for y in x]
plt.plot(tempo, X)
plt.plot(tempo, Y)
else:
plt.plot(tempo, x)
if salve:
plt.savefig(name)
plt.clf()
else:
plt.show()
plt.clf()
|
Gera um gráfico em Matplotlib de linha feito para demonstração grafica de sinais
Argumentos:
Tempo: Um numpy array com os valores do tempo
Sinal: Uma lista de numpy Array com os valores do sinal em relação ao tempo
Salve: 1 para gravar em PNG, 0 para exibir em Pop Up
Name: Nome do arquivo em caso de salvar png
Retorno:
Exibe um Grafico
|
PyLets/MatPlotWavelets.py
|
WaleMatPlot
|
matiasfreitasguimaraes/PyLets
| 1
|
python
|
def WaleMatPlot(tempo, sinal, salve=1, name='Sinal.png', real=1):
'Gera um gráfico em Matplotlib de linha feito para demonstração grafica de sinais\n Argumentos: \n Tempo: Um numpy array com os valores do tempo\n Sinal: Uma lista de numpy Array com os valores do sinal em relação ao tempo\n Salve: 1 para gravar em PNG, 0 para exibir em Pop Up\n Name: Nome do arquivo em caso de salvar png\n Retorno:\n Exibe um Grafico\n \n '
plt.figure(2)
plt.ylabel('Amplitude')
plt.xlabel('Time [s]')
for x in sinal:
if real:
X = [d.real for d in x]
Y = [y.imag for y in x]
plt.plot(tempo, X)
plt.plot(tempo, Y)
else:
plt.plot(tempo, x)
if salve:
plt.savefig(name)
plt.clf()
else:
plt.show()
plt.clf()
|
def WaleMatPlot(tempo, sinal, salve=1, name='Sinal.png', real=1):
'Gera um gráfico em Matplotlib de linha feito para demonstração grafica de sinais\n Argumentos: \n Tempo: Um numpy array com os valores do tempo\n Sinal: Uma lista de numpy Array com os valores do sinal em relação ao tempo\n Salve: 1 para gravar em PNG, 0 para exibir em Pop Up\n Name: Nome do arquivo em caso de salvar png\n Retorno:\n Exibe um Grafico\n \n '
plt.figure(2)
plt.ylabel('Amplitude')
plt.xlabel('Time [s]')
for x in sinal:
if real:
X = [d.real for d in x]
Y = [y.imag for y in x]
plt.plot(tempo, X)
plt.plot(tempo, Y)
else:
plt.plot(tempo, x)
if salve:
plt.savefig(name)
plt.clf()
else:
plt.show()
plt.clf()<|docstring|>Gera um gráfico em Matplotlib de linha feito para demonstração grafica de sinais
Argumentos:
Tempo: Um numpy array com os valores do tempo
Sinal: Uma lista de numpy Array com os valores do sinal em relação ao tempo
Salve: 1 para gravar em PNG, 0 para exibir em Pop Up
Name: Nome do arquivo em caso de salvar png
Retorno:
Exibe um Grafico<|endoftext|>
|
265d51ff3b0abb133cb4e25d701b8771595b4d35316c0dea7a05806e782cd035
|
def TransFourierGraph(FourierAnalise, salve=1, name='Transformada Fourier.png'):
'Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de de Fourier\n Argumentos: \n FourierAnalise: Array da Transformada de de Fourier\n Salve: 1 para gravar em PNG, 0 para exibir em Pop Up\n Name: Nome do arquivo em caso de salvar png\n Retorno:\n Exibe um Grafico\n '
plt.figure()
plt.ylabel('Amplitude')
plt.xlabel('Frequency [Hz]')
plt.bar(FourierAnalise[0], FourierAnalise[1], width=FourierAnalise[2])
if salve:
plt.savefig(name)
plt.clf()
else:
plt.show()
plt.clf()
|
Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de de Fourier
Argumentos:
FourierAnalise: Array da Transformada de de Fourier
Salve: 1 para gravar em PNG, 0 para exibir em Pop Up
Name: Nome do arquivo em caso de salvar png
Retorno:
Exibe um Grafico
|
PyLets/MatPlotWavelets.py
|
TransFourierGraph
|
matiasfreitasguimaraes/PyLets
| 1
|
python
|
def TransFourierGraph(FourierAnalise, salve=1, name='Transformada Fourier.png'):
'Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de de Fourier\n Argumentos: \n FourierAnalise: Array da Transformada de de Fourier\n Salve: 1 para gravar em PNG, 0 para exibir em Pop Up\n Name: Nome do arquivo em caso de salvar png\n Retorno:\n Exibe um Grafico\n '
plt.figure()
plt.ylabel('Amplitude')
plt.xlabel('Frequency [Hz]')
plt.bar(FourierAnalise[0], FourierAnalise[1], width=FourierAnalise[2])
if salve:
plt.savefig(name)
plt.clf()
else:
plt.show()
plt.clf()
|
def TransFourierGraph(FourierAnalise, salve=1, name='Transformada Fourier.png'):
'Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de de Fourier\n Argumentos: \n FourierAnalise: Array da Transformada de de Fourier\n Salve: 1 para gravar em PNG, 0 para exibir em Pop Up\n Name: Nome do arquivo em caso de salvar png\n Retorno:\n Exibe um Grafico\n '
plt.figure()
plt.ylabel('Amplitude')
plt.xlabel('Frequency [Hz]')
plt.bar(FourierAnalise[0], FourierAnalise[1], width=FourierAnalise[2])
if salve:
plt.savefig(name)
plt.clf()
else:
plt.show()
plt.clf()<|docstring|>Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de de Fourier
Argumentos:
FourierAnalise: Array da Transformada de de Fourier
Salve: 1 para gravar em PNG, 0 para exibir em Pop Up
Name: Nome do arquivo em caso de salvar png
Retorno:
Exibe um Grafico<|endoftext|>
|
2119a891cc85895f5fd67009fcf8fe693c414fd693ccd76a2c6a2a30ee69f5fe
|
def TransWaleContGraph(Matrix, salve=1, name='Transformada Wavelet.png'):
'Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de Wavelet\n Argumentos: \n Matrix: Uma Numpy Matrix da Transformada de Wavelet\n Salve: 1 para gravar em PNG, 0 para exibir em Pop Up\n Name: Nome do arquivo em caso de salvar png\n Retorno:\n Exibe um Grafico\n \n '
plt.imshow(Matrix, cmap='PRGn', aspect='auto')
if salve:
plt.savefig(name)
plt.clf()
else:
plt.show()
plt.clf()
|
Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de Wavelet
Argumentos:
Matrix: Uma Numpy Matrix da Transformada de Wavelet
Salve: 1 para gravar em PNG, 0 para exibir em Pop Up
Name: Nome do arquivo em caso de salvar png
Retorno:
Exibe um Grafico
|
PyLets/MatPlotWavelets.py
|
TransWaleContGraph
|
matiasfreitasguimaraes/PyLets
| 1
|
python
|
def TransWaleContGraph(Matrix, salve=1, name='Transformada Wavelet.png'):
'Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de Wavelet\n Argumentos: \n Matrix: Uma Numpy Matrix da Transformada de Wavelet\n Salve: 1 para gravar em PNG, 0 para exibir em Pop Up\n Name: Nome do arquivo em caso de salvar png\n Retorno:\n Exibe um Grafico\n \n '
plt.imshow(Matrix, cmap='PRGn', aspect='auto')
if salve:
plt.savefig(name)
plt.clf()
else:
plt.show()
plt.clf()
|
def TransWaleContGraph(Matrix, salve=1, name='Transformada Wavelet.png'):
'Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de Wavelet\n Argumentos: \n Matrix: Uma Numpy Matrix da Transformada de Wavelet\n Salve: 1 para gravar em PNG, 0 para exibir em Pop Up\n Name: Nome do arquivo em caso de salvar png\n Retorno:\n Exibe um Grafico\n \n '
plt.imshow(Matrix, cmap='PRGn', aspect='auto')
if salve:
plt.savefig(name)
plt.clf()
else:
plt.show()
plt.clf()<|docstring|>Gera um gráfico em Matplotlib de linha feito para demonstração grafica da transformada de Wavelet
Argumentos:
Matrix: Uma Numpy Matrix da Transformada de Wavelet
Salve: 1 para gravar em PNG, 0 para exibir em Pop Up
Name: Nome do arquivo em caso de salvar png
Retorno:
Exibe um Grafico<|endoftext|>
|
43cfeba2819534589953161f8a06ddde8de56b4cf05660fa40aeadac4dffe034
|
def to_sym_square(*tensors):
'\n Returns the symmetric square matrix given by multiplying a tensor for its transpose\n\n Parameters\n ----------\n *tensors : Tensor...\n a sequence of tensors\n\n Returns\n -------\n Tensor or list\n the symmetric square matrix of the input tensor\n\n Raises\n ------\n AssertError\n if input is not a tensor\n '
out = [matmul(t, transpose(t)) for t in tensors]
return (out if (len(out) > 1) else out[0])
|
Returns the symmetric square matrix given by multiplying a tensor for its transpose
Parameters
----------
*tensors : Tensor...
a sequence of tensors
Returns
-------
Tensor or list
the symmetric square matrix of the input tensor
Raises
------
AssertError
if input is not a tensor
|
ACME/utility/to_sym_square.py
|
to_sym_square
|
mauriziokovacic/ACME
| 3
|
python
|
def to_sym_square(*tensors):
'\n Returns the symmetric square matrix given by multiplying a tensor for its transpose\n\n Parameters\n ----------\n *tensors : Tensor...\n a sequence of tensors\n\n Returns\n -------\n Tensor or list\n the symmetric square matrix of the input tensor\n\n Raises\n ------\n AssertError\n if input is not a tensor\n '
out = [matmul(t, transpose(t)) for t in tensors]
return (out if (len(out) > 1) else out[0])
|
def to_sym_square(*tensors):
'\n Returns the symmetric square matrix given by multiplying a tensor for its transpose\n\n Parameters\n ----------\n *tensors : Tensor...\n a sequence of tensors\n\n Returns\n -------\n Tensor or list\n the symmetric square matrix of the input tensor\n\n Raises\n ------\n AssertError\n if input is not a tensor\n '
out = [matmul(t, transpose(t)) for t in tensors]
return (out if (len(out) > 1) else out[0])<|docstring|>Returns the symmetric square matrix given by multiplying a tensor for its transpose
Parameters
----------
*tensors : Tensor...
a sequence of tensors
Returns
-------
Tensor or list
the symmetric square matrix of the input tensor
Raises
------
AssertError
if input is not a tensor<|endoftext|>
|
952b806456c183c032c219121b91a250abb11d6e383ea00075319d4e2b434170
|
def grfcbk_size(args):
'\n Grammar rule function callback: **size**. This function will count the size of\n first item in argument list.\n\n :param list args: List of function arguments.\n :return: Size of the first item in argument list.\n :rtype: int\n '
return len(args[0])
|
Grammar rule function callback: **size**. This function will count the size of
first item in argument list.
:param list args: List of function arguments.
:return: Size of the first item in argument list.
:rtype: int
|
pynspect/filters.py
|
grfcbk_size
|
hruskraj/pynspect
| 0
|
python
|
def grfcbk_size(args):
'\n Grammar rule function callback: **size**. This function will count the size of\n first item in argument list.\n\n :param list args: List of function arguments.\n :return: Size of the first item in argument list.\n :rtype: int\n '
return len(args[0])
|
def grfcbk_size(args):
'\n Grammar rule function callback: **size**. This function will count the size of\n first item in argument list.\n\n :param list args: List of function arguments.\n :return: Size of the first item in argument list.\n :rtype: int\n '
return len(args[0])<|docstring|>Grammar rule function callback: **size**. This function will count the size of
first item in argument list.
:param list args: List of function arguments.
:return: Size of the first item in argument list.
:rtype: int<|endoftext|>
|
ebb6ec3664ec26ade18fb9397a294be78a828b93a3bc1caeb308e0043bb263cc
|
def grfcbk_strlen(args):
'\n Grammar rule function callback: **strlen**. This function will measure the\n string length of all subitems of the first item in argument list.\n\n :param list args: List of function arguments.\n :return: Length of all subitems of the first item in argument list.\n :rtype: int or list\n '
if (not args[0]):
return None
if isinstance(args[0], list):
return [len(x) for x in args[0]]
return len(args[0])
|
Grammar rule function callback: **strlen**. This function will measure the
string length of all subitems of the first item in argument list.
:param list args: List of function arguments.
:return: Length of all subitems of the first item in argument list.
:rtype: int or list
|
pynspect/filters.py
|
grfcbk_strlen
|
hruskraj/pynspect
| 0
|
python
|
def grfcbk_strlen(args):
'\n Grammar rule function callback: **strlen**. This function will measure the\n string length of all subitems of the first item in argument list.\n\n :param list args: List of function arguments.\n :return: Length of all subitems of the first item in argument list.\n :rtype: int or list\n '
if (not args[0]):
return None
if isinstance(args[0], list):
return [len(x) for x in args[0]]
return len(args[0])
|
def grfcbk_strlen(args):
'\n Grammar rule function callback: **strlen**. This function will measure the\n string length of all subitems of the first item in argument list.\n\n :param list args: List of function arguments.\n :return: Length of all subitems of the first item in argument list.\n :rtype: int or list\n '
if (not args[0]):
return None
if isinstance(args[0], list):
return [len(x) for x in args[0]]
return len(args[0])<|docstring|>Grammar rule function callback: **strlen**. This function will measure the
string length of all subitems of the first item in argument list.
:param list args: List of function arguments.
:return: Length of all subitems of the first item in argument list.
:rtype: int or list<|endoftext|>
|
8d457e3684cc589b73ca62457fa4e3adae38f19eada9fdced02289d5d8047693
|
def grfcbk_time(args):
'\n Grammar rule function callback: **time**. This function will call the\n :py:func:`time.time` function and return the result.\n\n :param list args: List of function arguments. Should be empty, but\n :return: The time in seconds since the epoch as a floating point number.\n :rtype: float\n '
if args:
raise FilteringRuleException("The 'time' function does not take any arguments.")
return time.time()
|
Grammar rule function callback: **time**. This function will call the
:py:func:`time.time` function and return the result.
:param list args: List of function arguments. Should be empty, but
:return: The time in seconds since the epoch as a floating point number.
:rtype: float
|
pynspect/filters.py
|
grfcbk_time
|
hruskraj/pynspect
| 0
|
python
|
def grfcbk_time(args):
'\n Grammar rule function callback: **time**. This function will call the\n :py:func:`time.time` function and return the result.\n\n :param list args: List of function arguments. Should be empty, but\n :return: The time in seconds since the epoch as a floating point number.\n :rtype: float\n '
if args:
raise FilteringRuleException("The 'time' function does not take any arguments.")
return time.time()
|
def grfcbk_time(args):
'\n Grammar rule function callback: **time**. This function will call the\n :py:func:`time.time` function and return the result.\n\n :param list args: List of function arguments. Should be empty, but\n :return: The time in seconds since the epoch as a floating point number.\n :rtype: float\n '
if args:
raise FilteringRuleException("The 'time' function does not take any arguments.")
return time.time()<|docstring|>Grammar rule function callback: **time**. This function will call the
:py:func:`time.time` function and return the result.
:param list args: List of function arguments. Should be empty, but
:return: The time in seconds since the epoch as a floating point number.
:rtype: float<|endoftext|>
|
be6adc6ec51659d0e2481988ace5f31f10a33d09e97362bfdaf87fa8c1bdcf3d
|
def grfcbk_utcnow(args):
'\n Grammar rule function callback: **utcnow**. This function will call the\n :py:func:`datetime.datetime.utcnow` function and return the result.\n\n :param list args: List of function arguments. Should be empty, but\n :return: Current datetime in UTC timezone.\n :rtype: datetime.datetime\n '
if args:
raise FilteringRuleException("The 'utcnow' function does not take any arguments.")
return datetime.datetime.utcnow()
|
Grammar rule function callback: **utcnow**. This function will call the
:py:func:`datetime.datetime.utcnow` function and return the result.
:param list args: List of function arguments. Should be empty, but
:return: Current datetime in UTC timezone.
:rtype: datetime.datetime
|
pynspect/filters.py
|
grfcbk_utcnow
|
hruskraj/pynspect
| 0
|
python
|
def grfcbk_utcnow(args):
'\n Grammar rule function callback: **utcnow**. This function will call the\n :py:func:`datetime.datetime.utcnow` function and return the result.\n\n :param list args: List of function arguments. Should be empty, but\n :return: Current datetime in UTC timezone.\n :rtype: datetime.datetime\n '
if args:
raise FilteringRuleException("The 'utcnow' function does not take any arguments.")
return datetime.datetime.utcnow()
|
def grfcbk_utcnow(args):
'\n Grammar rule function callback: **utcnow**. This function will call the\n :py:func:`datetime.datetime.utcnow` function and return the result.\n\n :param list args: List of function arguments. Should be empty, but\n :return: Current datetime in UTC timezone.\n :rtype: datetime.datetime\n '
if args:
raise FilteringRuleException("The 'utcnow' function does not take any arguments.")
return datetime.datetime.utcnow()<|docstring|>Grammar rule function callback: **utcnow**. This function will call the
:py:func:`datetime.datetime.utcnow` function and return the result.
:param list args: List of function arguments. Should be empty, but
:return: Current datetime in UTC timezone.
:rtype: datetime.datetime<|endoftext|>
|
29af4cc617f8251ca6f00bf3f51991b7947c90d720adb5e2c50fd89f0a687802
|
def prepare(self, rule):
'\n Parse and/or compile given rule into rule tree.\n\n :param rule: Filtering grammar rule.\n :return: Parsed and/or compiled rule.\n '
if self.parser:
rule = self.parser.parse(rule)
if self.compiler:
rule = self.compiler.compile(rule)
return rule
|
Parse and/or compile given rule into rule tree.
:param rule: Filtering grammar rule.
:return: Parsed and/or compiled rule.
|
pynspect/filters.py
|
prepare
|
hruskraj/pynspect
| 0
|
python
|
def prepare(self, rule):
'\n Parse and/or compile given rule into rule tree.\n\n :param rule: Filtering grammar rule.\n :return: Parsed and/or compiled rule.\n '
if self.parser:
rule = self.parser.parse(rule)
if self.compiler:
rule = self.compiler.compile(rule)
return rule
|
def prepare(self, rule):
'\n Parse and/or compile given rule into rule tree.\n\n :param rule: Filtering grammar rule.\n :return: Parsed and/or compiled rule.\n '
if self.parser:
rule = self.parser.parse(rule)
if self.compiler:
rule = self.compiler.compile(rule)
return rule<|docstring|>Parse and/or compile given rule into rule tree.
:param rule: Filtering grammar rule.
:return: Parsed and/or compiled rule.<|endoftext|>
|
b1fda5b99476562ec3eb5303491fc60d558b06588cbde9603ea7452faa793c0e
|
def filter(self, rule, data):
'\n Apply given filtering rule to given data structure.\n\n :param pynspect.rules.Rule rule: filtering rule to be checked\n :param any data: data structure to check against rule, ussually dict\n :return: True or False or expression result\n :rtype: bool or any\n '
return rule.traverse(self, obj=data)
|
Apply given filtering rule to given data structure.
:param pynspect.rules.Rule rule: filtering rule to be checked
:param any data: data structure to check against rule, ussually dict
:return: True or False or expression result
:rtype: bool or any
|
pynspect/filters.py
|
filter
|
hruskraj/pynspect
| 0
|
python
|
def filter(self, rule, data):
'\n Apply given filtering rule to given data structure.\n\n :param pynspect.rules.Rule rule: filtering rule to be checked\n :param any data: data structure to check against rule, ussually dict\n :return: True or False or expression result\n :rtype: bool or any\n '
return rule.traverse(self, obj=data)
|
def filter(self, rule, data):
'\n Apply given filtering rule to given data structure.\n\n :param pynspect.rules.Rule rule: filtering rule to be checked\n :param any data: data structure to check against rule, ussually dict\n :return: True or False or expression result\n :rtype: bool or any\n '
return rule.traverse(self, obj=data)<|docstring|>Apply given filtering rule to given data structure.
:param pynspect.rules.Rule rule: filtering rule to be checked
:param any data: data structure to check against rule, ussually dict
:return: True or False or expression result
:rtype: bool or any<|endoftext|>
|
f1d8bdc36cd5371e38d7d3226d8cfe2242186c3721c996e4714d337a13e6121f
|
def ipv4(self, rule, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.ipv4` interface.\n '
return rule.value
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.ipv4` interface.
|
pynspect/filters.py
|
ipv4
|
hruskraj/pynspect
| 0
|
python
|
def ipv4(self, rule, **kwargs):
'\n \n '
return rule.value
|
def ipv4(self, rule, **kwargs):
'\n \n '
return rule.value<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.ipv4` interface.<|endoftext|>
|
73c36681918cca6d48cbf973e555497d7dd3fa60459bedaa767eb0f1ccd1dfa1
|
def ipv6(self, rule, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.ipv6` interface.\n '
return rule.value
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.ipv6` interface.
|
pynspect/filters.py
|
ipv6
|
hruskraj/pynspect
| 0
|
python
|
def ipv6(self, rule, **kwargs):
'\n \n '
return rule.value
|
def ipv6(self, rule, **kwargs):
'\n \n '
return rule.value<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.ipv6` interface.<|endoftext|>
|
20e7ee1269b075baf8b2ae61d98d28f06306997b38aeb1ee690ce40eeb1d30c2
|
def datetime(self, rule, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.datetime` interface.\n '
return rule.value
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.datetime` interface.
|
pynspect/filters.py
|
datetime
|
hruskraj/pynspect
| 0
|
python
|
def datetime(self, rule, **kwargs):
'\n \n '
return rule.value
|
def datetime(self, rule, **kwargs):
'\n \n '
return rule.value<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.datetime` interface.<|endoftext|>
|
2f58e3a8a0847f5e48a6065dec756bb11a4e6ec9b87a37555e90abeed3d8f701
|
def timedelta(self, rule, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.timedelta` interface.\n '
return rule.value
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.timedelta` interface.
|
pynspect/filters.py
|
timedelta
|
hruskraj/pynspect
| 0
|
python
|
def timedelta(self, rule, **kwargs):
'\n \n '
return rule.value
|
def timedelta(self, rule, **kwargs):
'\n \n '
return rule.value<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.timedelta` interface.<|endoftext|>
|
c02abfd6d008e6393de5ff0974869035f29520bf493321e8a4975b6bf7ced3b1
|
def integer(self, rule, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.integer` interface.\n '
return rule.value
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.integer` interface.
|
pynspect/filters.py
|
integer
|
hruskraj/pynspect
| 0
|
python
|
def integer(self, rule, **kwargs):
'\n \n '
return rule.value
|
def integer(self, rule, **kwargs):
'\n \n '
return rule.value<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.integer` interface.<|endoftext|>
|
4b715b56c5130b1f445323a7dbe2467264ae9bd81b8649b100c1065f72390484
|
def float(self, rule, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.float` interface.\n '
return rule.value
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.float` interface.
|
pynspect/filters.py
|
float
|
hruskraj/pynspect
| 0
|
python
|
def float(self, rule, **kwargs):
'\n \n '
return rule.value
|
def float(self, rule, **kwargs):
'\n \n '
return rule.value<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.float` interface.<|endoftext|>
|
9e5acc38b7109febf54b342fc38edc28f370dd0050700e8c2fc060f8f2fca49c
|
def constant(self, rule, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.constant` interface.\n '
return rule.value
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.constant` interface.
|
pynspect/filters.py
|
constant
|
hruskraj/pynspect
| 0
|
python
|
def constant(self, rule, **kwargs):
'\n \n '
return rule.value
|
def constant(self, rule, **kwargs):
'\n \n '
return rule.value<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.constant` interface.<|endoftext|>
|
17ee104224ae725cf2eae40b8fa1ffe8983b720999f3279245d5e9b2bd909dbf
|
def variable(self, rule, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.variable` interface.\n '
return jpath_values(kwargs['obj'], rule.value)
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.variable` interface.
|
pynspect/filters.py
|
variable
|
hruskraj/pynspect
| 0
|
python
|
def variable(self, rule, **kwargs):
'\n \n '
return jpath_values(kwargs['obj'], rule.value)
|
def variable(self, rule, **kwargs):
'\n \n '
return jpath_values(kwargs['obj'], rule.value)<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.variable` interface.<|endoftext|>
|
208387be41b963af2fa5200762b037186771474890e98f65a0cb417ab3d805bb
|
def list(self, rule, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.list` interface.\n '
return rule.values()
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.list` interface.
|
pynspect/filters.py
|
list
|
hruskraj/pynspect
| 0
|
python
|
def list(self, rule, **kwargs):
'\n \n '
return rule.values()
|
def list(self, rule, **kwargs):
'\n \n '
return rule.values()<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.list` interface.<|endoftext|>
|
207b660a805e5fb5a9bfc0dbc6c13d6788296e6752efa60c580f4f2069fdc9b5
|
def binary_operation_logical(self, rule, left, right, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_logical` interface.\n '
return self.evaluate_binop_logical(rule.operation, left, right, **kwargs)
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_logical` interface.
|
pynspect/filters.py
|
binary_operation_logical
|
hruskraj/pynspect
| 0
|
python
|
def binary_operation_logical(self, rule, left, right, **kwargs):
'\n \n '
return self.evaluate_binop_logical(rule.operation, left, right, **kwargs)
|
def binary_operation_logical(self, rule, left, right, **kwargs):
'\n \n '
return self.evaluate_binop_logical(rule.operation, left, right, **kwargs)<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_logical` interface.<|endoftext|>
|
251610a16de08665e079ca9ba594a51b734fc608b5ee27465f5439c299c67d85
|
def binary_operation_comparison(self, rule, left, right, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_comparison` interface.\n '
return self.evaluate_binop_comparison(rule.operation, left, right, **kwargs)
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_comparison` interface.
|
pynspect/filters.py
|
binary_operation_comparison
|
hruskraj/pynspect
| 0
|
python
|
def binary_operation_comparison(self, rule, left, right, **kwargs):
'\n \n '
return self.evaluate_binop_comparison(rule.operation, left, right, **kwargs)
|
def binary_operation_comparison(self, rule, left, right, **kwargs):
'\n \n '
return self.evaluate_binop_comparison(rule.operation, left, right, **kwargs)<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_comparison` interface.<|endoftext|>
|
a56214b773ec5ee5623e551abb0eade71c563470cb42ac4f7626d92fcb51a2db
|
def binary_operation_math(self, rule, left, right, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_math` interface.\n '
return self.evaluate_binop_math(rule.operation, left, right, **kwargs)
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_math` interface.
|
pynspect/filters.py
|
binary_operation_math
|
hruskraj/pynspect
| 0
|
python
|
def binary_operation_math(self, rule, left, right, **kwargs):
'\n \n '
return self.evaluate_binop_math(rule.operation, left, right, **kwargs)
|
def binary_operation_math(self, rule, left, right, **kwargs):
'\n \n '
return self.evaluate_binop_math(rule.operation, left, right, **kwargs)<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_math` interface.<|endoftext|>
|
d2566f1bb699fbc38c78a18ae91491a7520de6d0fba76d3b0d911f46946e2239
|
def unary_operation(self, rule, right, **kwargs):
'\n Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.unary_operation` interface.\n '
return self.evaluate_unop(rule.operation, right, **kwargs)
|
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.unary_operation` interface.
|
pynspect/filters.py
|
unary_operation
|
hruskraj/pynspect
| 0
|
python
|
def unary_operation(self, rule, right, **kwargs):
'\n \n '
return self.evaluate_unop(rule.operation, right, **kwargs)
|
def unary_operation(self, rule, right, **kwargs):
'\n \n '
return self.evaluate_unop(rule.operation, right, **kwargs)<|docstring|>Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.unary_operation` interface.<|endoftext|>
|
f9d417bd19da1d572bf145a4e6f251cb8c006bf46789b943e6c1267cf35b0008
|
def parsleyfy(klass):
'A decorator to add {prefix}-* attributes to your form.fields'
old_init = klass.__init__
def new_init(self, *args, **kwargs):
old_init(self, *args, **kwargs)
prefix = getattr(getattr(self, 'Meta', None), 'parsley_namespace', 'data-parsley')
for (_, field) in self.fields.items():
update_widget_attrs(field, prefix)
extras = getattr(getattr(self, 'Meta', None), 'parsley_extras', {})
for (field_name, data) in extras.items():
for (key, value) in data.items():
if (field_name not in self.fields):
continue
attrs = self.fields[field_name].widget.attrs
if (key == 'equalto'):
value = ('#' + self[value].id_for_label)
if isinstance(value, bool):
value = ('true' if value else 'false')
attrs[('{prefix}-%s'.format(prefix=prefix) % key)] = value
klass.__init__ = new_init
return klass
|
A decorator to add {prefix}-* attributes to your form.fields
|
parsley/decorators.py
|
parsleyfy
|
percipient/Django-parsley
| 0
|
python
|
def parsleyfy(klass):
old_init = klass.__init__
def new_init(self, *args, **kwargs):
old_init(self, *args, **kwargs)
prefix = getattr(getattr(self, 'Meta', None), 'parsley_namespace', 'data-parsley')
for (_, field) in self.fields.items():
update_widget_attrs(field, prefix)
extras = getattr(getattr(self, 'Meta', None), 'parsley_extras', {})
for (field_name, data) in extras.items():
for (key, value) in data.items():
if (field_name not in self.fields):
continue
attrs = self.fields[field_name].widget.attrs
if (key == 'equalto'):
value = ('#' + self[value].id_for_label)
if isinstance(value, bool):
value = ('true' if value else 'false')
attrs[('{prefix}-%s'.format(prefix=prefix) % key)] = value
klass.__init__ = new_init
return klass
|
def parsleyfy(klass):
old_init = klass.__init__
def new_init(self, *args, **kwargs):
old_init(self, *args, **kwargs)
prefix = getattr(getattr(self, 'Meta', None), 'parsley_namespace', 'data-parsley')
for (_, field) in self.fields.items():
update_widget_attrs(field, prefix)
extras = getattr(getattr(self, 'Meta', None), 'parsley_extras', {})
for (field_name, data) in extras.items():
for (key, value) in data.items():
if (field_name not in self.fields):
continue
attrs = self.fields[field_name].widget.attrs
if (key == 'equalto'):
value = ('#' + self[value].id_for_label)
if isinstance(value, bool):
value = ('true' if value else 'false')
attrs[('{prefix}-%s'.format(prefix=prefix) % key)] = value
klass.__init__ = new_init
return klass<|docstring|>A decorator to add {prefix}-* attributes to your form.fields<|endoftext|>
|
1500810c351c2ed6efc772b5b8f72ea9372544e710f7b30b27c2758106bbbe5d
|
def generate_vault_list():
'Generate random list of vault UUIDs'
vault_list = []
random_int = random.randint(1, 10)
while (random_int > 0):
vault_list.append({'vault_id': uuid.uuid4().hex})
random_int -= 1
return vault_list
|
Generate random list of vault UUIDs
|
otcextensions/tests/unit/osclient/cbr/v3/fakes.py
|
generate_vault_list
|
ameszi/python-otcextensions
| 9
|
python
|
def generate_vault_list():
vault_list = []
random_int = random.randint(1, 10)
while (random_int > 0):
vault_list.append({'vault_id': uuid.uuid4().hex})
random_int -= 1
return vault_list
|
def generate_vault_list():
vault_list = []
random_int = random.randint(1, 10)
while (random_int > 0):
vault_list.append({'vault_id': uuid.uuid4().hex})
random_int -= 1
return vault_list<|docstring|>Generate random list of vault UUIDs<|endoftext|>
|
00a4632d93cd541872d41b9ad961d59e042e43d935e7efae217e223f54322da0
|
def generate_pattern_list():
'Generate random list of patterns'
pattern_list = []
random_int = random.randint(1, 5)
while (random_int > 0):
pattern_list.append(generate_pattern())
random_int -= 1
return pattern_list
|
Generate random list of patterns
|
otcextensions/tests/unit/osclient/cbr/v3/fakes.py
|
generate_pattern_list
|
ameszi/python-otcextensions
| 9
|
python
|
def generate_pattern_list():
pattern_list = []
random_int = random.randint(1, 5)
while (random_int > 0):
pattern_list.append(generate_pattern())
random_int -= 1
return pattern_list
|
def generate_pattern_list():
pattern_list = []
random_int = random.randint(1, 5)
while (random_int > 0):
pattern_list.append(generate_pattern())
random_int -= 1
return pattern_list<|docstring|>Generate random list of patterns<|endoftext|>
|
878ced3ee4f60ce725f80bd3873eb60a8d6894fb682ff953569dc5b4d13a4fee
|
def get_player_pages(soup, player_list):
'scrape URLs from one page'
tag_list = soup.find_all('a', class_='row_link')
for tag in tag_list:
if ('href' in tag.attrs):
player_list.append(tag.attrs['href'])
return player_list
|
scrape URLs from one page
|
python_code_examples/scraping/mls_pages_v2.py
|
get_player_pages
|
gotoplanb/python-adv-web-apps
| 34
|
python
|
def get_player_pages(soup, player_list):
tag_list = soup.find_all('a', class_='row_link')
for tag in tag_list:
if ('href' in tag.attrs):
player_list.append(tag.attrs['href'])
return player_list
|
def get_player_pages(soup, player_list):
tag_list = soup.find_all('a', class_='row_link')
for tag in tag_list:
if ('href' in tag.attrs):
player_list.append(tag.attrs['href'])
return player_list<|docstring|>scrape URLs from one page<|endoftext|>
|
5cb0f3cfcbb9a5ea38a00d417e4f56888a79b6fe6f141a7b806f74a6aa85cdac
|
def _iter_frames(initialFrame):
'NO-YIELD VERSION: Iterates through all the frames starting at the specified frame (which will be the first returned item)'
frames = []
while (initialFrame is not None):
frames.append(initialFrame)
initialFrame = initialFrame.f_back
return frames
|
NO-YIELD VERSION: Iterates through all the frames starting at the specified frame (which will be the first returned item)
|
python/helpers/pydev/_pydevd_bundle/pydevd_vars.py
|
_iter_frames
|
protector1990/intellij-community
| 2
|
python
|
def _iter_frames(initialFrame):
frames = []
while (initialFrame is not None):
frames.append(initialFrame)
initialFrame = initialFrame.f_back
return frames
|
def _iter_frames(initialFrame):
frames = []
while (initialFrame is not None):
frames.append(initialFrame)
initialFrame = initialFrame.f_back
return frames<|docstring|>NO-YIELD VERSION: Iterates through all the frames starting at the specified frame (which will be the first returned item)<|endoftext|>
|
950d562d62989dd72a63307a32a0f2b217ed537b43bc16b440cc0da2bfea84c3
|
def find_frame(thread_id, frame_id):
' returns a frame on the thread that has a given frame_id '
try:
curr_thread_id = get_thread_id(threading.currentThread())
if (thread_id != curr_thread_id):
try:
return get_custom_frame(thread_id, frame_id)
except:
pass
raise VariableError(('find_frame: must execute on same thread (%s != %s)' % (thread_id, curr_thread_id)))
lookingFor = int(frame_id)
if AdditionalFramesContainer.additional_frames:
if (thread_id in AdditionalFramesContainer.additional_frames):
frame = AdditionalFramesContainer.additional_frames[thread_id].get(lookingFor)
if (frame is not None):
return frame
curFrame = get_frame()
if (frame_id == '*'):
return curFrame
frameFound = None
for frame in _iter_frames(curFrame):
if (lookingFor == id(frame)):
frameFound = frame
del frame
break
del frame
del curFrame
if (frameFound is None):
msgFrames = ''
i = 0
for frame in _iter_frames(get_frame()):
i += 1
msgFrames += str(id(frame))
if ((i % 5) == 0):
msgFrames += '\n'
else:
msgFrames += ' - '
errMsg = ('find_frame: frame not found.\n Looking for thread_id:%s, frame_id:%s\n Current thread_id:%s, available frames:\n %s\n\n ' % (thread_id, lookingFor, curr_thread_id, msgFrames))
sys.stderr.write(errMsg)
return None
return frameFound
except:
import traceback
traceback.print_exc()
return None
|
returns a frame on the thread that has a given frame_id
|
python/helpers/pydev/_pydevd_bundle/pydevd_vars.py
|
find_frame
|
protector1990/intellij-community
| 2
|
python
|
def find_frame(thread_id, frame_id):
' '
try:
curr_thread_id = get_thread_id(threading.currentThread())
if (thread_id != curr_thread_id):
try:
return get_custom_frame(thread_id, frame_id)
except:
pass
raise VariableError(('find_frame: must execute on same thread (%s != %s)' % (thread_id, curr_thread_id)))
lookingFor = int(frame_id)
if AdditionalFramesContainer.additional_frames:
if (thread_id in AdditionalFramesContainer.additional_frames):
frame = AdditionalFramesContainer.additional_frames[thread_id].get(lookingFor)
if (frame is not None):
return frame
curFrame = get_frame()
if (frame_id == '*'):
return curFrame
frameFound = None
for frame in _iter_frames(curFrame):
if (lookingFor == id(frame)):
frameFound = frame
del frame
break
del frame
del curFrame
if (frameFound is None):
msgFrames =
i = 0
for frame in _iter_frames(get_frame()):
i += 1
msgFrames += str(id(frame))
if ((i % 5) == 0):
msgFrames += '\n'
else:
msgFrames += ' - '
errMsg = ('find_frame: frame not found.\n Looking for thread_id:%s, frame_id:%s\n Current thread_id:%s, available frames:\n %s\n\n ' % (thread_id, lookingFor, curr_thread_id, msgFrames))
sys.stderr.write(errMsg)
return None
return frameFound
except:
import traceback
traceback.print_exc()
return None
|
def find_frame(thread_id, frame_id):
' '
try:
curr_thread_id = get_thread_id(threading.currentThread())
if (thread_id != curr_thread_id):
try:
return get_custom_frame(thread_id, frame_id)
except:
pass
raise VariableError(('find_frame: must execute on same thread (%s != %s)' % (thread_id, curr_thread_id)))
lookingFor = int(frame_id)
if AdditionalFramesContainer.additional_frames:
if (thread_id in AdditionalFramesContainer.additional_frames):
frame = AdditionalFramesContainer.additional_frames[thread_id].get(lookingFor)
if (frame is not None):
return frame
curFrame = get_frame()
if (frame_id == '*'):
return curFrame
frameFound = None
for frame in _iter_frames(curFrame):
if (lookingFor == id(frame)):
frameFound = frame
del frame
break
del frame
del curFrame
if (frameFound is None):
msgFrames =
i = 0
for frame in _iter_frames(get_frame()):
i += 1
msgFrames += str(id(frame))
if ((i % 5) == 0):
msgFrames += '\n'
else:
msgFrames += ' - '
errMsg = ('find_frame: frame not found.\n Looking for thread_id:%s, frame_id:%s\n Current thread_id:%s, available frames:\n %s\n\n ' % (thread_id, lookingFor, curr_thread_id, msgFrames))
sys.stderr.write(errMsg)
return None
return frameFound
except:
import traceback
traceback.print_exc()
return None<|docstring|>returns a frame on the thread that has a given frame_id<|endoftext|>
|
0b2f16cc971b48599466bf19a76d7b15eb3f49f1cf103b8a40a8ca50c786dece
|
def getVariable(thread_id, frame_id, scope, attrs):
"\n returns the value of a variable\n\n :scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME\n\n BY_ID means we'll traverse the list of all objects alive to get the object.\n\n :attrs: after reaching the proper scope, we have to get the attributes until we find\n the proper location (i.e.: obj\tattr1\tattr2)\n\n :note: when BY_ID is used, the frame_id is considered the id of the object to find and\n not the frame (as we don't care about the frame in this case).\n "
if (scope == 'BY_ID'):
if (thread_id != get_thread_id(threading.currentThread())):
raise VariableError('getVariable: must execute on same thread')
try:
import gc
objects = gc.get_objects()
except:
pass
else:
frame_id = int(frame_id)
for var in objects:
if (id(var) == frame_id):
if (attrs is not None):
attrList = attrs.split('\t')
for k in attrList:
(_type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
return var
sys.stderr.write(('Unable to find object with id: %s\n' % (frame_id,)))
return None
frame = find_frame(thread_id, frame_id)
if (frame is None):
return {}
if (attrs is not None):
attrList = attrs.split('\t')
else:
attrList = []
for attr in attrList:
attr.replace('@_@TAB_CHAR@_@', '\t')
if (scope == 'EXPRESSION'):
for count in xrange(len(attrList)):
if (count == 0):
var = evaluate_expression(thread_id, frame_id, attrList[count], False)
else:
(_type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, attrList[count])
else:
if (scope == 'GLOBAL'):
var = frame.f_globals
del attrList[0]
else:
var = {}
var.update(frame.f_globals)
var.update(frame.f_locals)
for k in attrList:
(_type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
return var
|
returns the value of a variable
:scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME
BY_ID means we'll traverse the list of all objects alive to get the object.
:attrs: after reaching the proper scope, we have to get the attributes until we find
the proper location (i.e.: obj attr1 attr2)
:note: when BY_ID is used, the frame_id is considered the id of the object to find and
not the frame (as we don't care about the frame in this case).
|
python/helpers/pydev/_pydevd_bundle/pydevd_vars.py
|
getVariable
|
protector1990/intellij-community
| 2
|
python
|
def getVariable(thread_id, frame_id, scope, attrs):
"\n returns the value of a variable\n\n :scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME\n\n BY_ID means we'll traverse the list of all objects alive to get the object.\n\n :attrs: after reaching the proper scope, we have to get the attributes until we find\n the proper location (i.e.: obj\tattr1\tattr2)\n\n :note: when BY_ID is used, the frame_id is considered the id of the object to find and\n not the frame (as we don't care about the frame in this case).\n "
if (scope == 'BY_ID'):
if (thread_id != get_thread_id(threading.currentThread())):
raise VariableError('getVariable: must execute on same thread')
try:
import gc
objects = gc.get_objects()
except:
pass
else:
frame_id = int(frame_id)
for var in objects:
if (id(var) == frame_id):
if (attrs is not None):
attrList = attrs.split('\t')
for k in attrList:
(_type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
return var
sys.stderr.write(('Unable to find object with id: %s\n' % (frame_id,)))
return None
frame = find_frame(thread_id, frame_id)
if (frame is None):
return {}
if (attrs is not None):
attrList = attrs.split('\t')
else:
attrList = []
for attr in attrList:
attr.replace('@_@TAB_CHAR@_@', '\t')
if (scope == 'EXPRESSION'):
for count in xrange(len(attrList)):
if (count == 0):
var = evaluate_expression(thread_id, frame_id, attrList[count], False)
else:
(_type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, attrList[count])
else:
if (scope == 'GLOBAL'):
var = frame.f_globals
del attrList[0]
else:
var = {}
var.update(frame.f_globals)
var.update(frame.f_locals)
for k in attrList:
(_type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
return var
|
def getVariable(thread_id, frame_id, scope, attrs):
"\n returns the value of a variable\n\n :scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME\n\n BY_ID means we'll traverse the list of all objects alive to get the object.\n\n :attrs: after reaching the proper scope, we have to get the attributes until we find\n the proper location (i.e.: obj\tattr1\tattr2)\n\n :note: when BY_ID is used, the frame_id is considered the id of the object to find and\n not the frame (as we don't care about the frame in this case).\n "
if (scope == 'BY_ID'):
if (thread_id != get_thread_id(threading.currentThread())):
raise VariableError('getVariable: must execute on same thread')
try:
import gc
objects = gc.get_objects()
except:
pass
else:
frame_id = int(frame_id)
for var in objects:
if (id(var) == frame_id):
if (attrs is not None):
attrList = attrs.split('\t')
for k in attrList:
(_type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
return var
sys.stderr.write(('Unable to find object with id: %s\n' % (frame_id,)))
return None
frame = find_frame(thread_id, frame_id)
if (frame is None):
return {}
if (attrs is not None):
attrList = attrs.split('\t')
else:
attrList = []
for attr in attrList:
attr.replace('@_@TAB_CHAR@_@', '\t')
if (scope == 'EXPRESSION'):
for count in xrange(len(attrList)):
if (count == 0):
var = evaluate_expression(thread_id, frame_id, attrList[count], False)
else:
(_type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, attrList[count])
else:
if (scope == 'GLOBAL'):
var = frame.f_globals
del attrList[0]
else:
var = {}
var.update(frame.f_globals)
var.update(frame.f_locals)
for k in attrList:
(_type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
return var<|docstring|>returns the value of a variable
:scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME
BY_ID means we'll traverse the list of all objects alive to get the object.
:attrs: after reaching the proper scope, we have to get the attributes until we find
the proper location (i.e.: obj attr1 attr2)
:note: when BY_ID is used, the frame_id is considered the id of the object to find and
not the frame (as we don't care about the frame in this case).<|endoftext|>
|
04bc75a17cc818e3806347bf58d033c450c8e4de45ec7659b24d457afce96478
|
def resolve_compound_variable_fields(thread_id, frame_id, scope, attrs):
"\n Resolve compound variable in debugger scopes by its name and attributes\n\n :param thread_id: id of the variable's thread\n :param frame_id: id of the variable's frame\n :param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME\n :param attrs: after reaching the proper scope, we have to get the attributes until we find\n the proper location (i.e.: obj\tattr1\tattr2)\n :return: a dictionary of variables's fields\n "
var = getVariable(thread_id, frame_id, scope, attrs)
try:
(_type, _typeName, resolver) = get_type(var)
return (_typeName, resolver.get_dictionary(var))
except:
sys.stderr.write(('Error evaluating: thread_id: %s\nframe_id: %s\nscope: %s\nattrs: %s\n' % (thread_id, frame_id, scope, attrs)))
traceback.print_exc()
|
Resolve compound variable in debugger scopes by its name and attributes
:param thread_id: id of the variable's thread
:param frame_id: id of the variable's frame
:param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME
:param attrs: after reaching the proper scope, we have to get the attributes until we find
the proper location (i.e.: obj attr1 attr2)
:return: a dictionary of variables's fields
|
python/helpers/pydev/_pydevd_bundle/pydevd_vars.py
|
resolve_compound_variable_fields
|
protector1990/intellij-community
| 2
|
python
|
def resolve_compound_variable_fields(thread_id, frame_id, scope, attrs):
"\n Resolve compound variable in debugger scopes by its name and attributes\n\n :param thread_id: id of the variable's thread\n :param frame_id: id of the variable's frame\n :param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME\n :param attrs: after reaching the proper scope, we have to get the attributes until we find\n the proper location (i.e.: obj\tattr1\tattr2)\n :return: a dictionary of variables's fields\n "
var = getVariable(thread_id, frame_id, scope, attrs)
try:
(_type, _typeName, resolver) = get_type(var)
return (_typeName, resolver.get_dictionary(var))
except:
sys.stderr.write(('Error evaluating: thread_id: %s\nframe_id: %s\nscope: %s\nattrs: %s\n' % (thread_id, frame_id, scope, attrs)))
traceback.print_exc()
|
def resolve_compound_variable_fields(thread_id, frame_id, scope, attrs):
"\n Resolve compound variable in debugger scopes by its name and attributes\n\n :param thread_id: id of the variable's thread\n :param frame_id: id of the variable's frame\n :param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME\n :param attrs: after reaching the proper scope, we have to get the attributes until we find\n the proper location (i.e.: obj\tattr1\tattr2)\n :return: a dictionary of variables's fields\n "
var = getVariable(thread_id, frame_id, scope, attrs)
try:
(_type, _typeName, resolver) = get_type(var)
return (_typeName, resolver.get_dictionary(var))
except:
sys.stderr.write(('Error evaluating: thread_id: %s\nframe_id: %s\nscope: %s\nattrs: %s\n' % (thread_id, frame_id, scope, attrs)))
traceback.print_exc()<|docstring|>Resolve compound variable in debugger scopes by its name and attributes
:param thread_id: id of the variable's thread
:param frame_id: id of the variable's frame
:param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME
:param attrs: after reaching the proper scope, we have to get the attributes until we find
the proper location (i.e.: obj attr1 attr2)
:return: a dictionary of variables's fields<|endoftext|>
|
882ac7bff2572c21332ba6159006d2094a4afae66d772232b4daea7027cada49
|
def resolve_var_object(var, attrs):
"\n Resolve variable's attribute\n\n :param var: an object of variable\n :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2)\n :return: a value of resolved variable's attribute\n "
if (attrs is not None):
attr_list = attrs.split('\t')
else:
attr_list = []
for k in attr_list:
(type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
return var
|
Resolve variable's attribute
:param var: an object of variable
:param attrs: a sequence of variable's attributes separated by (i.e.: obj attr1 attr2)
:return: a value of resolved variable's attribute
|
python/helpers/pydev/_pydevd_bundle/pydevd_vars.py
|
resolve_var_object
|
protector1990/intellij-community
| 2
|
python
|
def resolve_var_object(var, attrs):
"\n Resolve variable's attribute\n\n :param var: an object of variable\n :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2)\n :return: a value of resolved variable's attribute\n "
if (attrs is not None):
attr_list = attrs.split('\t')
else:
attr_list = []
for k in attr_list:
(type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
return var
|
def resolve_var_object(var, attrs):
"\n Resolve variable's attribute\n\n :param var: an object of variable\n :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2)\n :return: a value of resolved variable's attribute\n "
if (attrs is not None):
attr_list = attrs.split('\t')
else:
attr_list = []
for k in attr_list:
(type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
return var<|docstring|>Resolve variable's attribute
:param var: an object of variable
:param attrs: a sequence of variable's attributes separated by (i.e.: obj attr1 attr2)
:return: a value of resolved variable's attribute<|endoftext|>
|
01b5fd328d28e8003127d487625319cad60face1320639e99c3d88095ffeb5ae
|
def resolve_compound_var_object_fields(var, attrs):
"\n Resolve compound variable by its object and attributes\n\n :param var: an object of variable\n :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2)\n :return: a dictionary of variables's fields\n "
attr_list = attrs.split('\t')
for k in attr_list:
(type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
try:
(type, _typeName, resolver) = get_type(var)
return resolver.get_dictionary(var)
except:
traceback.print_exc()
|
Resolve compound variable by its object and attributes
:param var: an object of variable
:param attrs: a sequence of variable's attributes separated by (i.e.: obj attr1 attr2)
:return: a dictionary of variables's fields
|
python/helpers/pydev/_pydevd_bundle/pydevd_vars.py
|
resolve_compound_var_object_fields
|
protector1990/intellij-community
| 2
|
python
|
def resolve_compound_var_object_fields(var, attrs):
"\n Resolve compound variable by its object and attributes\n\n :param var: an object of variable\n :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2)\n :return: a dictionary of variables's fields\n "
attr_list = attrs.split('\t')
for k in attr_list:
(type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
try:
(type, _typeName, resolver) = get_type(var)
return resolver.get_dictionary(var)
except:
traceback.print_exc()
|
def resolve_compound_var_object_fields(var, attrs):
"\n Resolve compound variable by its object and attributes\n\n :param var: an object of variable\n :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2)\n :return: a dictionary of variables's fields\n "
attr_list = attrs.split('\t')
for k in attr_list:
(type, _typeName, resolver) = get_type(var)
var = resolver.resolve(var, k)
try:
(type, _typeName, resolver) = get_type(var)
return resolver.get_dictionary(var)
except:
traceback.print_exc()<|docstring|>Resolve compound variable by its object and attributes
:param var: an object of variable
:param attrs: a sequence of variable's attributes separated by (i.e.: obj attr1 attr2)
:return: a dictionary of variables's fields<|endoftext|>
|
030d63ee6f0640697a155431f8d26e7890b9f90bb473a305907508295dd0f731
|
def custom_operation(thread_id, frame_id, scope, attrs, style, code_or_file, operation_fn_name):
"\n We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var.\n\n code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed.\n operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint)\n "
expressionValue = getVariable(thread_id, frame_id, scope, attrs)
try:
namespace = {'__name__': '<custom_operation>'}
if (style == 'EXECFILE'):
namespace['__file__'] = code_or_file
execfile(code_or_file, namespace, namespace)
else:
namespace['__file__'] = '<customOperationCode>'
Exec(code_or_file, namespace, namespace)
return str(namespace[operation_fn_name](expressionValue))
except:
traceback.print_exc()
|
We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var.
code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed.
operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint)
|
python/helpers/pydev/_pydevd_bundle/pydevd_vars.py
|
custom_operation
|
protector1990/intellij-community
| 2
|
python
|
def custom_operation(thread_id, frame_id, scope, attrs, style, code_or_file, operation_fn_name):
"\n We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var.\n\n code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed.\n operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint)\n "
expressionValue = getVariable(thread_id, frame_id, scope, attrs)
try:
namespace = {'__name__': '<custom_operation>'}
if (style == 'EXECFILE'):
namespace['__file__'] = code_or_file
execfile(code_or_file, namespace, namespace)
else:
namespace['__file__'] = '<customOperationCode>'
Exec(code_or_file, namespace, namespace)
return str(namespace[operation_fn_name](expressionValue))
except:
traceback.print_exc()
|
def custom_operation(thread_id, frame_id, scope, attrs, style, code_or_file, operation_fn_name):
"\n We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var.\n\n code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed.\n operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint)\n "
expressionValue = getVariable(thread_id, frame_id, scope, attrs)
try:
namespace = {'__name__': '<custom_operation>'}
if (style == 'EXECFILE'):
namespace['__file__'] = code_or_file
execfile(code_or_file, namespace, namespace)
else:
namespace['__file__'] = '<customOperationCode>'
Exec(code_or_file, namespace, namespace)
return str(namespace[operation_fn_name](expressionValue))
except:
traceback.print_exc()<|docstring|>We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var.
code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed.
operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint)<|endoftext|>
|
2cc396b060ecd23b4fccc0ac8303d66a5a5deb3eef06971537141c94e5eea12c
|
def evaluate_expression(thread_id, frame_id, expression, doExec):
'returns the result of the evaluated expression\n @param doExec: determines if we should do an exec or an eval\n '
frame = find_frame(thread_id, frame_id)
if (frame is None):
return
updated_globals = {}
updated_globals.update(frame.f_globals)
updated_globals.update(frame.f_locals)
try:
expression = str(expression.replace('@LINE@', '\n'))
if doExec:
try:
compiled = compile(expression, '<string>', 'eval')
except:
Exec(expression, updated_globals, frame.f_locals)
pydevd_save_locals.save_locals(frame)
else:
result = eval(compiled, updated_globals, frame.f_locals)
if (result is not None):
sys.stdout.write(('%s\n' % (result,)))
return
else:
return eval_in_context(expression, updated_globals, frame.f_locals)
finally:
del updated_globals
del frame
|
returns the result of the evaluated expression
@param doExec: determines if we should do an exec or an eval
|
python/helpers/pydev/_pydevd_bundle/pydevd_vars.py
|
evaluate_expression
|
protector1990/intellij-community
| 2
|
python
|
def evaluate_expression(thread_id, frame_id, expression, doExec):
'returns the result of the evaluated expression\n @param doExec: determines if we should do an exec or an eval\n '
frame = find_frame(thread_id, frame_id)
if (frame is None):
return
updated_globals = {}
updated_globals.update(frame.f_globals)
updated_globals.update(frame.f_locals)
try:
expression = str(expression.replace('@LINE@', '\n'))
if doExec:
try:
compiled = compile(expression, '<string>', 'eval')
except:
Exec(expression, updated_globals, frame.f_locals)
pydevd_save_locals.save_locals(frame)
else:
result = eval(compiled, updated_globals, frame.f_locals)
if (result is not None):
sys.stdout.write(('%s\n' % (result,)))
return
else:
return eval_in_context(expression, updated_globals, frame.f_locals)
finally:
del updated_globals
del frame
|
def evaluate_expression(thread_id, frame_id, expression, doExec):
'returns the result of the evaluated expression\n @param doExec: determines if we should do an exec or an eval\n '
frame = find_frame(thread_id, frame_id)
if (frame is None):
return
updated_globals = {}
updated_globals.update(frame.f_globals)
updated_globals.update(frame.f_locals)
try:
expression = str(expression.replace('@LINE@', '\n'))
if doExec:
try:
compiled = compile(expression, '<string>', 'eval')
except:
Exec(expression, updated_globals, frame.f_locals)
pydevd_save_locals.save_locals(frame)
else:
result = eval(compiled, updated_globals, frame.f_locals)
if (result is not None):
sys.stdout.write(('%s\n' % (result,)))
return
else:
return eval_in_context(expression, updated_globals, frame.f_locals)
finally:
del updated_globals
del frame<|docstring|>returns the result of the evaluated expression
@param doExec: determines if we should do an exec or an eval<|endoftext|>
|
7485662e092bc71af0744a9af65b8ededaed1936f5a9713071c25a9d68da97d9
|
def change_attr_expression(thread_id, frame_id, attr, expression, dbg, value=SENTINEL_VALUE):
'Changes some attribute in a given frame.\n '
frame = find_frame(thread_id, frame_id)
if (frame is None):
return
try:
expression = expression.replace('@LINE@', '\n')
if (dbg.plugin and (value is SENTINEL_VALUE)):
result = dbg.plugin.change_variable(frame, attr, expression)
if result:
return result
if (attr[:7] == 'Globals'):
attr = attr[8:]
if (attr in frame.f_globals):
if (value is SENTINEL_VALUE):
value = eval(expression, frame.f_globals, frame.f_locals)
frame.f_globals[attr] = value
return frame.f_globals[attr]
else:
if pydevd_save_locals.is_save_locals_available():
if (value is SENTINEL_VALUE):
value = eval(expression, frame.f_globals, frame.f_locals)
frame.f_locals[attr] = value
pydevd_save_locals.save_locals(frame)
return frame.f_locals[attr]
if (value is SENTINEL_VALUE):
value = eval(expression, frame.f_globals, frame.f_locals)
result = value
Exec(('%s=%s' % (attr, expression)), frame.f_globals, frame.f_locals)
return result
except Exception:
traceback.print_exc()
|
Changes some attribute in a given frame.
|
python/helpers/pydev/_pydevd_bundle/pydevd_vars.py
|
change_attr_expression
|
protector1990/intellij-community
| 2
|
python
|
def change_attr_expression(thread_id, frame_id, attr, expression, dbg, value=SENTINEL_VALUE):
'\n '
frame = find_frame(thread_id, frame_id)
if (frame is None):
return
try:
expression = expression.replace('@LINE@', '\n')
if (dbg.plugin and (value is SENTINEL_VALUE)):
result = dbg.plugin.change_variable(frame, attr, expression)
if result:
return result
if (attr[:7] == 'Globals'):
attr = attr[8:]
if (attr in frame.f_globals):
if (value is SENTINEL_VALUE):
value = eval(expression, frame.f_globals, frame.f_locals)
frame.f_globals[attr] = value
return frame.f_globals[attr]
else:
if pydevd_save_locals.is_save_locals_available():
if (value is SENTINEL_VALUE):
value = eval(expression, frame.f_globals, frame.f_locals)
frame.f_locals[attr] = value
pydevd_save_locals.save_locals(frame)
return frame.f_locals[attr]
if (value is SENTINEL_VALUE):
value = eval(expression, frame.f_globals, frame.f_locals)
result = value
Exec(('%s=%s' % (attr, expression)), frame.f_globals, frame.f_locals)
return result
except Exception:
traceback.print_exc()
|
def change_attr_expression(thread_id, frame_id, attr, expression, dbg, value=SENTINEL_VALUE):
'\n '
frame = find_frame(thread_id, frame_id)
if (frame is None):
return
try:
expression = expression.replace('@LINE@', '\n')
if (dbg.plugin and (value is SENTINEL_VALUE)):
result = dbg.plugin.change_variable(frame, attr, expression)
if result:
return result
if (attr[:7] == 'Globals'):
attr = attr[8:]
if (attr in frame.f_globals):
if (value is SENTINEL_VALUE):
value = eval(expression, frame.f_globals, frame.f_locals)
frame.f_globals[attr] = value
return frame.f_globals[attr]
else:
if pydevd_save_locals.is_save_locals_available():
if (value is SENTINEL_VALUE):
value = eval(expression, frame.f_globals, frame.f_locals)
frame.f_locals[attr] = value
pydevd_save_locals.save_locals(frame)
return frame.f_locals[attr]
if (value is SENTINEL_VALUE):
value = eval(expression, frame.f_globals, frame.f_locals)
result = value
Exec(('%s=%s' % (attr, expression)), frame.f_globals, frame.f_locals)
return result
except Exception:
traceback.print_exc()<|docstring|>Changes some attribute in a given frame.<|endoftext|>
|
80197d8cfebd7306a1dfe7ce5a660e38843867587f39270875110cfa45b38926
|
def dataframe_to_xml(df, name, roffset, coffset, rows, cols, format):
'\n :type df: pandas.core.frame.DataFrame\n :type name: str\n :type coffset: int\n :type roffset: int\n :type rows: int\n :type cols: int\n :type format: str\n\n\n '
dim = len(df.axes)
num_rows = df.shape[0]
num_cols = (df.shape[1] if (dim > 1) else 1)
xml = slice_to_xml(name, num_rows, num_cols, '', '', (0, 0))
if ((rows, cols) == ((- 1), (- 1))):
(rows, cols) = (num_rows, num_cols)
rows = min(rows, MAXIMUM_ARRAY_SIZE)
cols = min(cols, MAXIMUM_ARRAY_SIZE, num_cols)
col_bounds = ([None] * cols)
dtypes = ([None] * cols)
if (dim > 1):
for col in range(cols):
dtype = df.dtypes.iloc[(coffset + col)].kind
dtypes[col] = dtype
if (dtype in 'biufc'):
cvalues = df.iloc[(:, (coffset + col))]
bounds = (cvalues.min(), cvalues.max())
else:
bounds = (0, 0)
col_bounds[col] = bounds
else:
dtype = df.dtype.kind
dtypes[0] = dtype
col_bounds[0] = ((df.min(), df.max()) if (dtype in 'biufc') else (0, 0))
df = (df.iloc[(roffset:(roffset + rows), coffset:(coffset + cols))] if (dim > 1) else df.iloc[roffset:(roffset + rows)])
rows = df.shape[0]
cols = (df.shape[1] if (dim > 1) else 1)
format = format.replace('%', '')
def col_to_format(c):
return (format if ((dtypes[c] == 'f') and format) else array_default_format(dtypes[c]))
xml += header_data_to_xml(rows, cols, dtypes, col_bounds, col_to_format, df, dim)
xml += array_data_to_xml(rows, cols, (lambda r: ((('%' + col_to_format(c)) % (df.iat[(r, c)] if (dim > 1) else df.iat[r])) for c in range(cols))))
return xml
|
:type df: pandas.core.frame.DataFrame
:type name: str
:type coffset: int
:type roffset: int
:type rows: int
:type cols: int
:type format: str
|
python/helpers/pydev/_pydevd_bundle/pydevd_vars.py
|
dataframe_to_xml
|
protector1990/intellij-community
| 2
|
python
|
def dataframe_to_xml(df, name, roffset, coffset, rows, cols, format):
'\n :type df: pandas.core.frame.DataFrame\n :type name: str\n :type coffset: int\n :type roffset: int\n :type rows: int\n :type cols: int\n :type format: str\n\n\n '
dim = len(df.axes)
num_rows = df.shape[0]
num_cols = (df.shape[1] if (dim > 1) else 1)
xml = slice_to_xml(name, num_rows, num_cols, , , (0, 0))
if ((rows, cols) == ((- 1), (- 1))):
(rows, cols) = (num_rows, num_cols)
rows = min(rows, MAXIMUM_ARRAY_SIZE)
cols = min(cols, MAXIMUM_ARRAY_SIZE, num_cols)
col_bounds = ([None] * cols)
dtypes = ([None] * cols)
if (dim > 1):
for col in range(cols):
dtype = df.dtypes.iloc[(coffset + col)].kind
dtypes[col] = dtype
if (dtype in 'biufc'):
cvalues = df.iloc[(:, (coffset + col))]
bounds = (cvalues.min(), cvalues.max())
else:
bounds = (0, 0)
col_bounds[col] = bounds
else:
dtype = df.dtype.kind
dtypes[0] = dtype
col_bounds[0] = ((df.min(), df.max()) if (dtype in 'biufc') else (0, 0))
df = (df.iloc[(roffset:(roffset + rows), coffset:(coffset + cols))] if (dim > 1) else df.iloc[roffset:(roffset + rows)])
rows = df.shape[0]
cols = (df.shape[1] if (dim > 1) else 1)
format = format.replace('%', )
def col_to_format(c):
return (format if ((dtypes[c] == 'f') and format) else array_default_format(dtypes[c]))
xml += header_data_to_xml(rows, cols, dtypes, col_bounds, col_to_format, df, dim)
xml += array_data_to_xml(rows, cols, (lambda r: ((('%' + col_to_format(c)) % (df.iat[(r, c)] if (dim > 1) else df.iat[r])) for c in range(cols))))
return xml
|
def dataframe_to_xml(df, name, roffset, coffset, rows, cols, format):
'\n :type df: pandas.core.frame.DataFrame\n :type name: str\n :type coffset: int\n :type roffset: int\n :type rows: int\n :type cols: int\n :type format: str\n\n\n '
dim = len(df.axes)
num_rows = df.shape[0]
num_cols = (df.shape[1] if (dim > 1) else 1)
xml = slice_to_xml(name, num_rows, num_cols, , , (0, 0))
if ((rows, cols) == ((- 1), (- 1))):
(rows, cols) = (num_rows, num_cols)
rows = min(rows, MAXIMUM_ARRAY_SIZE)
cols = min(cols, MAXIMUM_ARRAY_SIZE, num_cols)
col_bounds = ([None] * cols)
dtypes = ([None] * cols)
if (dim > 1):
for col in range(cols):
dtype = df.dtypes.iloc[(coffset + col)].kind
dtypes[col] = dtype
if (dtype in 'biufc'):
cvalues = df.iloc[(:, (coffset + col))]
bounds = (cvalues.min(), cvalues.max())
else:
bounds = (0, 0)
col_bounds[col] = bounds
else:
dtype = df.dtype.kind
dtypes[0] = dtype
col_bounds[0] = ((df.min(), df.max()) if (dtype in 'biufc') else (0, 0))
df = (df.iloc[(roffset:(roffset + rows), coffset:(coffset + cols))] if (dim > 1) else df.iloc[roffset:(roffset + rows)])
rows = df.shape[0]
cols = (df.shape[1] if (dim > 1) else 1)
format = format.replace('%', )
def col_to_format(c):
return (format if ((dtypes[c] == 'f') and format) else array_default_format(dtypes[c]))
xml += header_data_to_xml(rows, cols, dtypes, col_bounds, col_to_format, df, dim)
xml += array_data_to_xml(rows, cols, (lambda r: ((('%' + col_to_format(c)) % (df.iat[(r, c)] if (dim > 1) else df.iat[r])) for c in range(cols))))
return xml<|docstring|>:type df: pandas.core.frame.DataFrame
:type name: str
:type coffset: int
:type roffset: int
:type rows: int
:type cols: int
:type format: str<|endoftext|>
|
e0143a4b259b01dbb3db8a07c7c3acc15dee32699c5427cc10a3ba90f4e5d426
|
def test_of_add_new_valid_contact(app):
'\n Validation of add correct new contact with full data\n '
app.contact.create(Contract(first_name=Profinity.correct_data, last_name=Profinity.correct_data, middle_name=Profinity.correct_data, nickname=Profinity.correct_data, title=Profinity.correct_data, company_name=Profinity.correct_data, address_name=Profinity.correct_data, work=Profinity.correct_phone_number, fax=Profinity.correct_phone_number, home=Profinity.correct_phone_number, mobile=Profinity.correct_phone_number, email1=Profinity.correct_email, email2=Profinity.correct_email, email3=Profinity.correct_email, homepage=Profinity.correct_data, add_year=True, address=Profinity.correct_data, phone=Profinity.correct_data, notes=Profinity.correct_data))
app.contact.delete_contract()
|
Validation of add correct new contact with full data
|
tests_contract/test_contract.py
|
test_of_add_new_valid_contact
|
werbk/task-3.8
| 0
|
python
|
def test_of_add_new_valid_contact(app):
'\n \n '
app.contact.create(Contract(first_name=Profinity.correct_data, last_name=Profinity.correct_data, middle_name=Profinity.correct_data, nickname=Profinity.correct_data, title=Profinity.correct_data, company_name=Profinity.correct_data, address_name=Profinity.correct_data, work=Profinity.correct_phone_number, fax=Profinity.correct_phone_number, home=Profinity.correct_phone_number, mobile=Profinity.correct_phone_number, email1=Profinity.correct_email, email2=Profinity.correct_email, email3=Profinity.correct_email, homepage=Profinity.correct_data, add_year=True, address=Profinity.correct_data, phone=Profinity.correct_data, notes=Profinity.correct_data))
app.contact.delete_contract()
|
def test_of_add_new_valid_contact(app):
'\n \n '
app.contact.create(Contract(first_name=Profinity.correct_data, last_name=Profinity.correct_data, middle_name=Profinity.correct_data, nickname=Profinity.correct_data, title=Profinity.correct_data, company_name=Profinity.correct_data, address_name=Profinity.correct_data, work=Profinity.correct_phone_number, fax=Profinity.correct_phone_number, home=Profinity.correct_phone_number, mobile=Profinity.correct_phone_number, email1=Profinity.correct_email, email2=Profinity.correct_email, email3=Profinity.correct_email, homepage=Profinity.correct_data, add_year=True, address=Profinity.correct_data, phone=Profinity.correct_data, notes=Profinity.correct_data))
app.contact.delete_contract()<|docstring|>Validation of add correct new contact with full data<|endoftext|>
|
a06a4a531be0daf4b48f3e15b128483d4bd92bdfb93dc67ee4b95d36f88d0711
|
def test_of_add_new_valid_contact_name_only(app):
'\n Validation of add correct new contact with only full name\n '
app.contact.create(Contract(first_name=Profinity.correct_data, last_name=Profinity.correct_data, middle_name=Profinity.correct_data, nickname=Profinity.correct_data))
app.contact.delete_contract()
|
Validation of add correct new contact with only full name
|
tests_contract/test_contract.py
|
test_of_add_new_valid_contact_name_only
|
werbk/task-3.8
| 0
|
python
|
def test_of_add_new_valid_contact_name_only(app):
'\n \n '
app.contact.create(Contract(first_name=Profinity.correct_data, last_name=Profinity.correct_data, middle_name=Profinity.correct_data, nickname=Profinity.correct_data))
app.contact.delete_contract()
|
def test_of_add_new_valid_contact_name_only(app):
'\n \n '
app.contact.create(Contract(first_name=Profinity.correct_data, last_name=Profinity.correct_data, middle_name=Profinity.correct_data, nickname=Profinity.correct_data))
app.contact.delete_contract()<|docstring|>Validation of add correct new contact with only full name<|endoftext|>
|
71cf00aa40380258156de1904092e19cf7b72625684fd4a91a1e6a30fab667d7
|
def bindings_to_list(bindings):
'Pystachio takes bindings in the form of a list of dictionaries. Each pystachio binding\n becomes another dictionary in the list. So we need to convert the bindings specified by\n the user from a list of "name=value" formatted strings to a list of the dictionaries \n expected by pystachio.\n '
result = []
for b in bindings:
binding_parts = b.split('=')
if (len(binding_parts) != 2):
raise ValueError('Binding parameter must be formatted name=value')
result.append({binding_parts[0]: binding_parts[1]})
return result
|
Pystachio takes bindings in the form of a list of dictionaries. Each pystachio binding
becomes another dictionary in the list. So we need to convert the bindings specified by
the user from a list of "name=value" formatted strings to a list of the dictionaries
expected by pystachio.
|
src/main/python/apache/aurora/client/cli/context.py
|
bindings_to_list
|
zmanji/incubator-aurora
| 0
|
python
|
def bindings_to_list(bindings):
'Pystachio takes bindings in the form of a list of dictionaries. Each pystachio binding\n becomes another dictionary in the list. So we need to convert the bindings specified by\n the user from a list of "name=value" formatted strings to a list of the dictionaries \n expected by pystachio.\n '
result = []
for b in bindings:
binding_parts = b.split('=')
if (len(binding_parts) != 2):
raise ValueError('Binding parameter must be formatted name=value')
result.append({binding_parts[0]: binding_parts[1]})
return result
|
def bindings_to_list(bindings):
'Pystachio takes bindings in the form of a list of dictionaries. Each pystachio binding\n becomes another dictionary in the list. So we need to convert the bindings specified by\n the user from a list of "name=value" formatted strings to a list of the dictionaries \n expected by pystachio.\n '
result = []
for b in bindings:
binding_parts = b.split('=')
if (len(binding_parts) != 2):
raise ValueError('Binding parameter must be formatted name=value')
result.append({binding_parts[0]: binding_parts[1]})
return result<|docstring|>Pystachio takes bindings in the form of a list of dictionaries. Each pystachio binding
becomes another dictionary in the list. So we need to convert the bindings specified by
the user from a list of "name=value" formatted strings to a list of the dictionaries
expected by pystachio.<|endoftext|>
|
f7db4f0d9d6bda6bba297141cb31ac05899f9ed10ec2a5f8b420b8031f1c6df3
|
def get_api(self, cluster):
'Gets an API object for a specified cluster\n Keeps the API handle cached, so that only one handle for each cluster will be created in a\n session.\n '
if (cluster not in self.apis):
api = make_client(cluster)
self.apis[cluster] = api
return self.apis[cluster]
|
Gets an API object for a specified cluster
Keeps the API handle cached, so that only one handle for each cluster will be created in a
session.
|
src/main/python/apache/aurora/client/cli/context.py
|
get_api
|
zmanji/incubator-aurora
| 0
|
python
|
def get_api(self, cluster):
'Gets an API object for a specified cluster\n Keeps the API handle cached, so that only one handle for each cluster will be created in a\n session.\n '
if (cluster not in self.apis):
api = make_client(cluster)
self.apis[cluster] = api
return self.apis[cluster]
|
def get_api(self, cluster):
'Gets an API object for a specified cluster\n Keeps the API handle cached, so that only one handle for each cluster will be created in a\n session.\n '
if (cluster not in self.apis):
api = make_client(cluster)
self.apis[cluster] = api
return self.apis[cluster]<|docstring|>Gets an API object for a specified cluster
Keeps the API handle cached, so that only one handle for each cluster will be created in a
session.<|endoftext|>
|
4f8fb96150da89f5f1e417349b4a3535c498b460a491e620cf93fdaa91ad229b
|
def get_job_config(self, jobkey, config_file):
'Loads a job configuration from a config file.'
jobname = jobkey.name
try:
with open(config_file, 'r') as fp:
self.print_log(TRANSCRIPT, ('Config: %s' % fp.readlines()))
bindings = (bindings_to_list(self.options.bindings) if self.options.bindings else None)
return get_config(jobname, config_file, self.options.read_json, bindings, select_cluster=jobkey.cluster, select_role=jobkey.role, select_env=jobkey.env)
except Exception as e:
raise self.CommandError(EXIT_INVALID_CONFIGURATION, ('Error loading configuration: %s' % e))
|
Loads a job configuration from a config file.
|
src/main/python/apache/aurora/client/cli/context.py
|
get_job_config
|
zmanji/incubator-aurora
| 0
|
python
|
def get_job_config(self, jobkey, config_file):
jobname = jobkey.name
try:
with open(config_file, 'r') as fp:
self.print_log(TRANSCRIPT, ('Config: %s' % fp.readlines()))
bindings = (bindings_to_list(self.options.bindings) if self.options.bindings else None)
return get_config(jobname, config_file, self.options.read_json, bindings, select_cluster=jobkey.cluster, select_role=jobkey.role, select_env=jobkey.env)
except Exception as e:
raise self.CommandError(EXIT_INVALID_CONFIGURATION, ('Error loading configuration: %s' % e))
|
def get_job_config(self, jobkey, config_file):
jobname = jobkey.name
try:
with open(config_file, 'r') as fp:
self.print_log(TRANSCRIPT, ('Config: %s' % fp.readlines()))
bindings = (bindings_to_list(self.options.bindings) if self.options.bindings else None)
return get_config(jobname, config_file, self.options.read_json, bindings, select_cluster=jobkey.cluster, select_role=jobkey.role, select_env=jobkey.env)
except Exception as e:
raise self.CommandError(EXIT_INVALID_CONFIGURATION, ('Error loading configuration: %s' % e))<|docstring|>Loads a job configuration from a config file.<|endoftext|>
|
b97d9921cde2aaf327d6bedfbf9650e9c0177bdfcafe1e3cf0848b0371c72a23
|
def open_job_page(self, api, jobkey):
'Opens the page for a job in the system web browser.'
self.open_page(synthesize_url(api.scheduler_proxy.scheduler_client().url, jobkey.role, jobkey.env, jobkey.name))
|
Opens the page for a job in the system web browser.
|
src/main/python/apache/aurora/client/cli/context.py
|
open_job_page
|
zmanji/incubator-aurora
| 0
|
python
|
def open_job_page(self, api, jobkey):
self.open_page(synthesize_url(api.scheduler_proxy.scheduler_client().url, jobkey.role, jobkey.env, jobkey.name))
|
def open_job_page(self, api, jobkey):
self.open_page(synthesize_url(api.scheduler_proxy.scheduler_client().url, jobkey.role, jobkey.env, jobkey.name))<|docstring|>Opens the page for a job in the system web browser.<|endoftext|>
|
0e6cdf7f377a485b3e8c4362a05a262b98891730766ead756edad90f62e7a5d2
|
def open_scheduler_page(self, cluster, role, env, name):
'Open a scheduler page'
api = self.get_api(cluster)
self.open_page(synthesize_url(api.scheduler_proxy.scheduler_client().url, role, env, name))
|
Open a scheduler page
|
src/main/python/apache/aurora/client/cli/context.py
|
open_scheduler_page
|
zmanji/incubator-aurora
| 0
|
python
|
def open_scheduler_page(self, cluster, role, env, name):
api = self.get_api(cluster)
self.open_page(synthesize_url(api.scheduler_proxy.scheduler_client().url, role, env, name))
|
def open_scheduler_page(self, cluster, role, env, name):
api = self.get_api(cluster)
self.open_page(synthesize_url(api.scheduler_proxy.scheduler_client().url, role, env, name))<|docstring|>Open a scheduler page<|endoftext|>
|
b1e2f6953c3a876a7e90c0259e77ba7e217e6467338ff38d3591e5879ce5db53
|
@classmethod
def parse_partial_jobkey(cls, key):
'Given a partial jobkey, where parts can be wildcards, parse it.\n Slots that are wildcards will be replaced by "*".\n '
parts = []
for part in key.split('/'):
parts.append(part)
if (len(parts) > 4):
raise cls.CommandError(EXIT_INVALID_PARAMETER, 'Job key must have no more than 4 segments')
while (len(parts) < 4):
parts.append('*')
return PartialJobKey(*parts)
|
Given a partial jobkey, where parts can be wildcards, parse it.
Slots that are wildcards will be replaced by "*".
|
src/main/python/apache/aurora/client/cli/context.py
|
parse_partial_jobkey
|
zmanji/incubator-aurora
| 0
|
python
|
@classmethod
def parse_partial_jobkey(cls, key):
'Given a partial jobkey, where parts can be wildcards, parse it.\n Slots that are wildcards will be replaced by "*".\n '
parts = []
for part in key.split('/'):
parts.append(part)
if (len(parts) > 4):
raise cls.CommandError(EXIT_INVALID_PARAMETER, 'Job key must have no more than 4 segments')
while (len(parts) < 4):
parts.append('*')
return PartialJobKey(*parts)
|
@classmethod
def parse_partial_jobkey(cls, key):
'Given a partial jobkey, where parts can be wildcards, parse it.\n Slots that are wildcards will be replaced by "*".\n '
parts = []
for part in key.split('/'):
parts.append(part)
if (len(parts) > 4):
raise cls.CommandError(EXIT_INVALID_PARAMETER, 'Job key must have no more than 4 segments')
while (len(parts) < 4):
parts.append('*')
return PartialJobKey(*parts)<|docstring|>Given a partial jobkey, where parts can be wildcards, parse it.
Slots that are wildcards will be replaced by "*".<|endoftext|>
|
23402c8acb547014d981a8baff230d02b8f32ab11d5e0fabfc4a219d4e7dce5b
|
def get_job_list(self, clusters, role=None):
'Get a list of jobs from a group of clusters.\n :param clusters: the clusters to query for jobs\n :param role: if specified, only return jobs for the role; otherwise, return all jobs.\n '
result = []
if ('*' in role):
role = None
for cluster in clusters:
api = self.get_api(cluster)
resp = api.get_jobs(role)
self.check_and_log_response(resp, err_code=EXIT_COMMAND_FAILURE)
result.extend([AuroraJobKey(cluster, job.key.role, job.key.environment, job.key.name) for job in resp.result.getJobsResult.configs])
return result
|
Get a list of jobs from a group of clusters.
:param clusters: the clusters to query for jobs
:param role: if specified, only return jobs for the role; otherwise, return all jobs.
|
src/main/python/apache/aurora/client/cli/context.py
|
get_job_list
|
zmanji/incubator-aurora
| 0
|
python
|
def get_job_list(self, clusters, role=None):
'Get a list of jobs from a group of clusters.\n :param clusters: the clusters to query for jobs\n :param role: if specified, only return jobs for the role; otherwise, return all jobs.\n '
result = []
if ('*' in role):
role = None
for cluster in clusters:
api = self.get_api(cluster)
resp = api.get_jobs(role)
self.check_and_log_response(resp, err_code=EXIT_COMMAND_FAILURE)
result.extend([AuroraJobKey(cluster, job.key.role, job.key.environment, job.key.name) for job in resp.result.getJobsResult.configs])
return result
|
def get_job_list(self, clusters, role=None):
'Get a list of jobs from a group of clusters.\n :param clusters: the clusters to query for jobs\n :param role: if specified, only return jobs for the role; otherwise, return all jobs.\n '
result = []
if ('*' in role):
role = None
for cluster in clusters:
api = self.get_api(cluster)
resp = api.get_jobs(role)
self.check_and_log_response(resp, err_code=EXIT_COMMAND_FAILURE)
result.extend([AuroraJobKey(cluster, job.key.role, job.key.environment, job.key.name) for job in resp.result.getJobsResult.configs])
return result<|docstring|>Get a list of jobs from a group of clusters.
:param clusters: the clusters to query for jobs
:param role: if specified, only return jobs for the role; otherwise, return all jobs.<|endoftext|>
|
0b0ea5d2fc360dcead85ee58856a71f0cf4453949e46857558b1356ed49c963d
|
def get_jobs_matching_key(self, key):
'Finds all jobs matching a key containing wildcard segments.\n This is potentially slow!\n TODO(mchucarroll): insert a warning to users about slowness if the key contains wildcards!\n '
def is_fully_bound(key):
'Helper that checks if a key contains wildcards.'
return (not any((('*' in component) for component in [key.cluster, key.role, key.env, key.name])))
def filter_job_list(jobs, role, env, name):
'Filter a list of jobs to get just the jobs that match the pattern from a key'
return [job for job in jobs if (fnmatch(job.role, role) and fnmatch(job.env, env) and fnmatch(job.name, name))]
if (key.cluster == '*'):
clusters_to_search = CLUSTERS
else:
clusters_to_search = [key.cluster]
if is_fully_bound(key):
return [AuroraJobKey(key.cluster, key.role, key.env, key.name)]
else:
jobs = filter_job_list(self.get_job_list(clusters_to_search, key.role), key.role, key.env, key.name)
return jobs
|
Finds all jobs matching a key containing wildcard segments.
This is potentially slow!
TODO(mchucarroll): insert a warning to users about slowness if the key contains wildcards!
|
src/main/python/apache/aurora/client/cli/context.py
|
get_jobs_matching_key
|
zmanji/incubator-aurora
| 0
|
python
|
def get_jobs_matching_key(self, key):
'Finds all jobs matching a key containing wildcard segments.\n This is potentially slow!\n TODO(mchucarroll): insert a warning to users about slowness if the key contains wildcards!\n '
def is_fully_bound(key):
'Helper that checks if a key contains wildcards.'
return (not any((('*' in component) for component in [key.cluster, key.role, key.env, key.name])))
def filter_job_list(jobs, role, env, name):
'Filter a list of jobs to get just the jobs that match the pattern from a key'
return [job for job in jobs if (fnmatch(job.role, role) and fnmatch(job.env, env) and fnmatch(job.name, name))]
if (key.cluster == '*'):
clusters_to_search = CLUSTERS
else:
clusters_to_search = [key.cluster]
if is_fully_bound(key):
return [AuroraJobKey(key.cluster, key.role, key.env, key.name)]
else:
jobs = filter_job_list(self.get_job_list(clusters_to_search, key.role), key.role, key.env, key.name)
return jobs
|
def get_jobs_matching_key(self, key):
'Finds all jobs matching a key containing wildcard segments.\n This is potentially slow!\n TODO(mchucarroll): insert a warning to users about slowness if the key contains wildcards!\n '
def is_fully_bound(key):
'Helper that checks if a key contains wildcards.'
return (not any((('*' in component) for component in [key.cluster, key.role, key.env, key.name])))
def filter_job_list(jobs, role, env, name):
'Filter a list of jobs to get just the jobs that match the pattern from a key'
return [job for job in jobs if (fnmatch(job.role, role) and fnmatch(job.env, env) and fnmatch(job.name, name))]
if (key.cluster == '*'):
clusters_to_search = CLUSTERS
else:
clusters_to_search = [key.cluster]
if is_fully_bound(key):
return [AuroraJobKey(key.cluster, key.role, key.env, key.name)]
else:
jobs = filter_job_list(self.get_job_list(clusters_to_search, key.role), key.role, key.env, key.name)
return jobs<|docstring|>Finds all jobs matching a key containing wildcard segments.
This is potentially slow!
TODO(mchucarroll): insert a warning to users about slowness if the key contains wildcards!<|endoftext|>
|
5c59ad326f29705acccb4288a3f239bb71e269ee32d112c4ae1b76f2f942e46b
|
def get_job_status(self, key):
'Returns a list of task instances running under the job.'
api = self.get_api(key.cluster)
resp = api.check_status(key)
self.check_and_log_response(resp, err_code=EXIT_INVALID_PARAMETER)
return (resp.result.scheduleStatusResult.tasks or None)
|
Returns a list of task instances running under the job.
|
src/main/python/apache/aurora/client/cli/context.py
|
get_job_status
|
zmanji/incubator-aurora
| 0
|
python
|
def get_job_status(self, key):
api = self.get_api(key.cluster)
resp = api.check_status(key)
self.check_and_log_response(resp, err_code=EXIT_INVALID_PARAMETER)
return (resp.result.scheduleStatusResult.tasks or None)
|
def get_job_status(self, key):
api = self.get_api(key.cluster)
resp = api.check_status(key)
self.check_and_log_response(resp, err_code=EXIT_INVALID_PARAMETER)
return (resp.result.scheduleStatusResult.tasks or None)<|docstring|>Returns a list of task instances running under the job.<|endoftext|>
|
6081eaf8afdc678ffec8ec84deef9da566e3e1b5f50ad262b28162e83e27fe2e
|
def get_active_instances(self, key):
'Returns a list of the currently active instances of a job'
return [task.assignedTask.instanceId for task in self.get_job_status(key)]
|
Returns a list of the currently active instances of a job
|
src/main/python/apache/aurora/client/cli/context.py
|
get_active_instances
|
zmanji/incubator-aurora
| 0
|
python
|
def get_active_instances(self, key):
return [task.assignedTask.instanceId for task in self.get_job_status(key)]
|
def get_active_instances(self, key):
return [task.assignedTask.instanceId for task in self.get_job_status(key)]<|docstring|>Returns a list of the currently active instances of a job<|endoftext|>
|
9fbfeb9d9954318a7e4c9d323f533d97d0c067bf99c5b8e869c7d33a433bb23a
|
def verify_shards_option_validity(self, jobkey, instances):
'Given a jobkey, does a getTasksStatus, and then checks that the specified instances\n are valid for the job.\n '
active_instances = self.get_active_instances(jobkey)
if (max(active_instances) < max(instances)):
raise self.CommandError(EXIT_INVALID_PARAMETER, ('Invalid shards parameter: %s only has %s shards' % (jobkey, max(active_instances))))
|
Given a jobkey, does a getTasksStatus, and then checks that the specified instances
are valid for the job.
|
src/main/python/apache/aurora/client/cli/context.py
|
verify_shards_option_validity
|
zmanji/incubator-aurora
| 0
|
python
|
def verify_shards_option_validity(self, jobkey, instances):
'Given a jobkey, does a getTasksStatus, and then checks that the specified instances\n are valid for the job.\n '
active_instances = self.get_active_instances(jobkey)
if (max(active_instances) < max(instances)):
raise self.CommandError(EXIT_INVALID_PARAMETER, ('Invalid shards parameter: %s only has %s shards' % (jobkey, max(active_instances))))
|
def verify_shards_option_validity(self, jobkey, instances):
'Given a jobkey, does a getTasksStatus, and then checks that the specified instances\n are valid for the job.\n '
active_instances = self.get_active_instances(jobkey)
if (max(active_instances) < max(instances)):
raise self.CommandError(EXIT_INVALID_PARAMETER, ('Invalid shards parameter: %s only has %s shards' % (jobkey, max(active_instances))))<|docstring|>Given a jobkey, does a getTasksStatus, and then checks that the specified instances
are valid for the job.<|endoftext|>
|
8258dffefe58a7899d8956e66cd3a332f02fd4a91c43064afaf7f2637c403c0b
|
def is_fully_bound(key):
'Helper that checks if a key contains wildcards.'
return (not any((('*' in component) for component in [key.cluster, key.role, key.env, key.name])))
|
Helper that checks if a key contains wildcards.
|
src/main/python/apache/aurora/client/cli/context.py
|
is_fully_bound
|
zmanji/incubator-aurora
| 0
|
python
|
def is_fully_bound(key):
return (not any((('*' in component) for component in [key.cluster, key.role, key.env, key.name])))
|
def is_fully_bound(key):
return (not any((('*' in component) for component in [key.cluster, key.role, key.env, key.name])))<|docstring|>Helper that checks if a key contains wildcards.<|endoftext|>
|
50f98f6bdeefb23ea7aa9ee6e5ddd0381485da3f916e9f6eb90d98f4fce54b4d
|
def filter_job_list(jobs, role, env, name):
'Filter a list of jobs to get just the jobs that match the pattern from a key'
return [job for job in jobs if (fnmatch(job.role, role) and fnmatch(job.env, env) and fnmatch(job.name, name))]
|
Filter a list of jobs to get just the jobs that match the pattern from a key
|
src/main/python/apache/aurora/client/cli/context.py
|
filter_job_list
|
zmanji/incubator-aurora
| 0
|
python
|
def filter_job_list(jobs, role, env, name):
return [job for job in jobs if (fnmatch(job.role, role) and fnmatch(job.env, env) and fnmatch(job.name, name))]
|
def filter_job_list(jobs, role, env, name):
return [job for job in jobs if (fnmatch(job.role, role) and fnmatch(job.env, env) and fnmatch(job.name, name))]<|docstring|>Filter a list of jobs to get just the jobs that match the pattern from a key<|endoftext|>
|
92cc6c75577afb761697595d1b150222a77fd267fbb5cd939b82ea6dc3381c61
|
def E(msg, err_type=ERROR.BUILD, is_fatal=True, stackframe=2):
'Log an error'
Logger.log_error(msg, err_type, is_fatal, Util.get_stackframe(stackframe))
|
Log an error
|
GlobifestLib/Log.py
|
E
|
dpkristensen/globifest
| 0
|
python
|
def E(msg, err_type=ERROR.BUILD, is_fatal=True, stackframe=2):
Logger.log_error(msg, err_type, is_fatal, Util.get_stackframe(stackframe))
|
def E(msg, err_type=ERROR.BUILD, is_fatal=True, stackframe=2):
Logger.log_error(msg, err_type, is_fatal, Util.get_stackframe(stackframe))<|docstring|>Log an error<|endoftext|>
|
a985e8a061668a835fcc8da88b899f5b750e6bef5c5e1fa3778d02318e51bcfd
|
def I(msg):
'Log an informational message'
Logger.log_msg(LEVEL.INFO, msg)
|
Log an informational message
|
GlobifestLib/Log.py
|
I
|
dpkristensen/globifest
| 0
|
python
|
def I(msg):
Logger.log_msg(LEVEL.INFO, msg)
|
def I(msg):
Logger.log_msg(LEVEL.INFO, msg)<|docstring|>Log an informational message<|endoftext|>
|
ebcf309655f8e851b69f25bed866d7be23094706b24c5984ceda07d999915510
|
def D(msg):
'Log a debug message'
Logger.log_msg(LEVEL.DEBUG, msg)
|
Log a debug message
|
GlobifestLib/Log.py
|
D
|
dpkristensen/globifest
| 0
|
python
|
def D(msg):
Logger.log_msg(LEVEL.DEBUG, msg)
|
def D(msg):
Logger.log_msg(LEVEL.DEBUG, msg)<|docstring|>Log a debug message<|endoftext|>
|
24aabdf39d68932a67a6c51b6c76cf406cc766f11a6a729ca65bbf82628b878b
|
def X(msg):
'Log an extremely detailed message'
Logger.log_msg(LEVEL.EXTREME, msg)
|
Log an extremely detailed message
|
GlobifestLib/Log.py
|
X
|
dpkristensen/globifest
| 0
|
python
|
def X(msg):
Logger.log_msg(LEVEL.EXTREME, msg)
|
def X(msg):
Logger.log_msg(LEVEL.EXTREME, msg)<|docstring|>Log an extremely detailed message<|endoftext|>
|
cf7ac0d53e10ebcaa19ea1a535772bd08dadc4dc9fd53c7c3039018a43b9d5ab
|
def get_type(self):
'Returns the ERROR type'
return (self.err_type + 1)
|
Returns the ERROR type
|
GlobifestLib/Log.py
|
get_type
|
dpkristensen/globifest
| 0
|
python
|
def get_type(self):
return (self.err_type + 1)
|
def get_type(self):
return (self.err_type + 1)<|docstring|>Returns the ERROR type<|endoftext|>
|
1ae5e1cab527c413477e4004ed5535f61c3b54e7a8537a24e221b7a518c403ce
|
def has_level(self, level):
'Static method'
return (self.verbosity_level >= level)
|
Static method
|
GlobifestLib/Log.py
|
has_level
|
dpkristensen/globifest
| 0
|
python
|
def has_level(self, level):
return (self.verbosity_level >= level)
|
def has_level(self, level):
return (self.verbosity_level >= level)<|docstring|>Static method<|endoftext|>
|
442fc5dd8e73d772786b0553f73d50a60275b51bb8c3e3b58c59f81e3e1b94ae
|
def log_msg(self, level, msg):
'Prints the message if it is allowed by the verbosity level'
if self.has_level(level):
print(msg, file=self.out_pipe)
|
Prints the message if it is allowed by the verbosity level
|
GlobifestLib/Log.py
|
log_msg
|
dpkristensen/globifest
| 0
|
python
|
def log_msg(self, level, msg):
if self.has_level(level):
print(msg, file=self.out_pipe)
|
def log_msg(self, level, msg):
if self.has_level(level):
print(msg, file=self.out_pipe)<|docstring|>Prints the message if it is allowed by the verbosity level<|endoftext|>
|
afbc41b1fac2a6e6a71b1038b2c7f21d488f13eeb9ff2eb3be17c643c189e2f3
|
def log_error(self, msg, err_type=ERROR.BUILD, is_fatal=True, frame=Util.get_stackframe(2)):
'Prints and raises an error message'
debug_info = ''
local_variables = None
if (frame and self.has_level(LEVEL.EXTREME)):
f_info = inspect.getframeinfo(frame)
fname = os.path.basename(f_info.filename)
debug_info = '[{}@{:d}] '.format(fname, f_info.lineno)
local_variables = frame.f_locals
print('{}Error: {}\n'.format(debug_info, msg), file=self.err_pipe)
if local_variables:
print('Locals:')
print(local_variables)
if is_fatal:
raise GlobifestException(err_type, msg)
|
Prints and raises an error message
|
GlobifestLib/Log.py
|
log_error
|
dpkristensen/globifest
| 0
|
python
|
def log_error(self, msg, err_type=ERROR.BUILD, is_fatal=True, frame=Util.get_stackframe(2)):
debug_info =
local_variables = None
if (frame and self.has_level(LEVEL.EXTREME)):
f_info = inspect.getframeinfo(frame)
fname = os.path.basename(f_info.filename)
debug_info = '[{}@{:d}] '.format(fname, f_info.lineno)
local_variables = frame.f_locals
print('{}Error: {}\n'.format(debug_info, msg), file=self.err_pipe)
if local_variables:
print('Locals:')
print(local_variables)
if is_fatal:
raise GlobifestException(err_type, msg)
|
def log_error(self, msg, err_type=ERROR.BUILD, is_fatal=True, frame=Util.get_stackframe(2)):
debug_info =
local_variables = None
if (frame and self.has_level(LEVEL.EXTREME)):
f_info = inspect.getframeinfo(frame)
fname = os.path.basename(f_info.filename)
debug_info = '[{}@{:d}] '.format(fname, f_info.lineno)
local_variables = frame.f_locals
print('{}Error: {}\n'.format(debug_info, msg), file=self.err_pipe)
if local_variables:
print('Locals:')
print(local_variables)
if is_fatal:
raise GlobifestException(err_type, msg)<|docstring|>Prints and raises an error message<|endoftext|>
|
c20fd7f9fa1c0d04df4a5b76381429b523fe9873dfebe977525658f4335a76bc
|
def set_err_pipe(self, pipe):
'Set the pipe for error messages'
self.err_pipe = pipe
|
Set the pipe for error messages
|
GlobifestLib/Log.py
|
set_err_pipe
|
dpkristensen/globifest
| 0
|
python
|
def set_err_pipe(self, pipe):
self.err_pipe = pipe
|
def set_err_pipe(self, pipe):
self.err_pipe = pipe<|docstring|>Set the pipe for error messages<|endoftext|>
|
fd45c6e5bd9e14487bd7006d7a90a0fcfba714ff0119eaf203643d50f289a082
|
def set_level(self, level):
'Set the minimum verbosity level for log messages'
self.verbosity_level = level
|
Set the minimum verbosity level for log messages
|
GlobifestLib/Log.py
|
set_level
|
dpkristensen/globifest
| 0
|
python
|
def set_level(self, level):
self.verbosity_level = level
|
def set_level(self, level):
self.verbosity_level = level<|docstring|>Set the minimum verbosity level for log messages<|endoftext|>
|
2efff5e307df7932797a4772261414af0695880a944a206708d3c24910f03f73
|
def set_out_pipe(self, pipe):
'Set the pipe for non-error messages'
self.out_pipe = pipe
|
Set the pipe for non-error messages
|
GlobifestLib/Log.py
|
set_out_pipe
|
dpkristensen/globifest
| 0
|
python
|
def set_out_pipe(self, pipe):
self.out_pipe = pipe
|
def set_out_pipe(self, pipe):
self.out_pipe = pipe<|docstring|>Set the pipe for non-error messages<|endoftext|>
|
53df6c45426c22ae82a7a9e30e9763d23a9a6f6248a185300c5e45fe6b963d4c
|
def __init__(self, debug_mode=False):
'\n Initialize the class\n '
self._debuggable = Util.Container(enabled=debug_mode, text='')
|
Initialize the class
|
GlobifestLib/Log.py
|
__init__
|
dpkristensen/globifest
| 0
|
python
|
def __init__(self, debug_mode=False):
'\n \n '
self._debuggable = Util.Container(enabled=debug_mode, text=)
|
def __init__(self, debug_mode=False):
'\n \n '
self._debuggable = Util.Container(enabled=debug_mode, text=)<|docstring|>Initialize the class<|endoftext|>
|
642ded1dce17dc16b936dbee4a4c411c532749770e594f12d0812c1465e7f3bf
|
def debug(self, debug_text):
'Write text to the debug log'
if self._debuggable.enabled:
self._debuggable.text += ('\n ' + debug_text)
|
Write text to the debug log
|
GlobifestLib/Log.py
|
debug
|
dpkristensen/globifest
| 0
|
python
|
def debug(self, debug_text):
if self._debuggable.enabled:
self._debuggable.text += ('\n ' + debug_text)
|
def debug(self, debug_text):
if self._debuggable.enabled:
self._debuggable.text += ('\n ' + debug_text)<|docstring|>Write text to the debug log<|endoftext|>
|
d2115f6df3120d93c63df4052f0be52540f459a9fe5d08761948a51dd3209f7c
|
def link_debug_log(self, parent):
"Link this object's debug log to the parent"
self._debuggable = parent._debuggable
|
Link this object's debug log to the parent
|
GlobifestLib/Log.py
|
link_debug_log
|
dpkristensen/globifest
| 0
|
python
|
def link_debug_log(self, parent):
self._debuggable = parent._debuggable
|
def link_debug_log(self, parent):
self._debuggable = parent._debuggable<|docstring|>Link this object's debug log to the parent<|endoftext|>
|
595b5b665ee9fa32286639a5816e37efbf9528ec2cd4ba52aff051a2f206af7a
|
def get_debug_mode(self):
'Return whether debugging is enabled for this object'
return self._debuggable.enabled
|
Return whether debugging is enabled for this object
|
GlobifestLib/Log.py
|
get_debug_mode
|
dpkristensen/globifest
| 0
|
python
|
def get_debug_mode(self):
return self._debuggable.enabled
|
def get_debug_mode(self):
return self._debuggable.enabled<|docstring|>Return whether debugging is enabled for this object<|endoftext|>
|
9471a31039121ec15d83fdc78de99bb91c05c307cf19783a84923f996e3b8423
|
def get_debug_log(self):
'Return the cached debug log from this object'
return self._debuggable.text
|
Return the cached debug log from this object
|
GlobifestLib/Log.py
|
get_debug_log
|
dpkristensen/globifest
| 0
|
python
|
def get_debug_log(self):
return self._debuggable.text
|
def get_debug_log(self):
return self._debuggable.text<|docstring|>Return the cached debug log from this object<|endoftext|>
|
67d8cac592d3ecf59b77bf8047f7c5a9a564a2b5a39e3e06781f2bd10cbe703c
|
def sort_array(num_list=[]):
'Takes in a list of numbers and returns it with the odd sorted and the even not'
if (type(num_list) != list):
raise TypeError('The argument for sort_array must be of type list.')
if (len(num_list) < 1):
return num_list
odd_list = []
odd_indices = []
for (i, num) in enumerate(num_list):
if ((num % 2) != 0):
odd_list.append(num)
odd_indices.append(i)
sorted_odd_list = quick_sort(odd_list)
final_list = copy(num_list)
for (i, num) in enumerate(sorted_odd_list):
final_index = odd_indices[i]
final_list[final_index] = num
return final_list
|
Takes in a list of numbers and returns it with the odd sorted and the even not
|
src/codewars/6-kyu/sort-the-odd/sort_the_odd.py
|
sort_array
|
nwthomas/code-challenges
| 1
|
python
|
def sort_array(num_list=[]):
if (type(num_list) != list):
raise TypeError('The argument for sort_array must be of type list.')
if (len(num_list) < 1):
return num_list
odd_list = []
odd_indices = []
for (i, num) in enumerate(num_list):
if ((num % 2) != 0):
odd_list.append(num)
odd_indices.append(i)
sorted_odd_list = quick_sort(odd_list)
final_list = copy(num_list)
for (i, num) in enumerate(sorted_odd_list):
final_index = odd_indices[i]
final_list[final_index] = num
return final_list
|
def sort_array(num_list=[]):
if (type(num_list) != list):
raise TypeError('The argument for sort_array must be of type list.')
if (len(num_list) < 1):
return num_list
odd_list = []
odd_indices = []
for (i, num) in enumerate(num_list):
if ((num % 2) != 0):
odd_list.append(num)
odd_indices.append(i)
sorted_odd_list = quick_sort(odd_list)
final_list = copy(num_list)
for (i, num) in enumerate(sorted_odd_list):
final_index = odd_indices[i]
final_list[final_index] = num
return final_list<|docstring|>Takes in a list of numbers and returns it with the odd sorted and the even not<|endoftext|>
|
e94d3803e8a87720ff6474b4789281c848860816a50ca82374bc7c62224ae108
|
def quick_sort(num_list=[]):
'Quick sorts a number list'
if (type(num_list) != list):
raise TypeError('The argument for quick_sort must be of type list.')
if (len(num_list) <= 1):
return num_list
choice = num_list[(len(num_list) // 2)]
greater = [num for num in num_list if (num > choice)]
equal = [num for num in num_list if (num == choice)]
lesser = [num for num in num_list if (num < choice)]
return ((quick_sort(lesser) + equal) + quick_sort(greater))
|
Quick sorts a number list
|
src/codewars/6-kyu/sort-the-odd/sort_the_odd.py
|
quick_sort
|
nwthomas/code-challenges
| 1
|
python
|
def quick_sort(num_list=[]):
if (type(num_list) != list):
raise TypeError('The argument for quick_sort must be of type list.')
if (len(num_list) <= 1):
return num_list
choice = num_list[(len(num_list) // 2)]
greater = [num for num in num_list if (num > choice)]
equal = [num for num in num_list if (num == choice)]
lesser = [num for num in num_list if (num < choice)]
return ((quick_sort(lesser) + equal) + quick_sort(greater))
|
def quick_sort(num_list=[]):
if (type(num_list) != list):
raise TypeError('The argument for quick_sort must be of type list.')
if (len(num_list) <= 1):
return num_list
choice = num_list[(len(num_list) // 2)]
greater = [num for num in num_list if (num > choice)]
equal = [num for num in num_list if (num == choice)]
lesser = [num for num in num_list if (num < choice)]
return ((quick_sort(lesser) + equal) + quick_sort(greater))<|docstring|>Quick sorts a number list<|endoftext|>
|
b416f02536b875ba7f8033eaebaab0c20e36d8d6ed5d779f1d9636bcfa219ea5
|
def init_main(self):
'\n Init Main Frame\n :return:\n '
panel = wx.Panel(self)
hbox = wx.BoxSizer(wx.HORIZONTAL)
fgs = wx.FlexGridSizer(5, 2, 10, 10)
hostname_label = wx.StaticText(panel, label='Hostname:')
self.hostname_choice = wx.ComboBox(panel, choices=self.hostnames, style=(wx.CB_READONLY | wx.CB_DROPDOWN))
self.Bind(wx.EVT_COMBOBOX_DROPDOWN, self.update_hostnames_handler, self.hostname_choice)
data_label = wx.StaticText(panel, label='Data:')
self.data_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
send_btn = wx.Button(panel, label='Send')
self.Bind(wx.EVT_BUTTON, self._send_data_handler, send_btn)
clear_btn = wx.Button(panel, label='Clear')
self.Bind(wx.EVT_BUTTON, self._clear_handler, clear_btn)
message = wx.StaticText(panel, label='Message')
self.message_text = wx.TextCtrl(panel, value='', style=(wx.TE_READONLY | wx.TE_MULTILINE))
log = wx.StaticText(panel, label='Log')
self.log_text = wx.TextCtrl(panel, value='', style=(wx.TE_READONLY | wx.TE_MULTILINE))
fgs.AddMany([hostname_label, (self.hostname_choice, 1, wx.EXPAND), (data_label, 1, wx.EXPAND), (self.data_text, 1, wx.EXPAND), (clear_btn, 1, wx.EXPAND), (send_btn, 1, wx.EXPAND), (message, 1, wx.EXPAND), (self.message_text, 1, wx.EXPAND), (log, 1, wx.EXPAND), (self.log_text, 1, wx.EXPAND)])
fgs.AddGrowableRow(1, 1)
fgs.AddGrowableRow(3, 1)
fgs.AddGrowableRow(4, 1)
fgs.AddGrowableCol(1, 1)
hbox.Add(fgs, proportion=2, flag=(wx.ALL | wx.EXPAND), border=15)
panel.SetSizer(hbox)
|
Init Main Frame
:return:
|
src/routing/content_frame.py
|
init_main
|
VinaLx/routing-simulation
| 2
|
python
|
def init_main(self):
'\n Init Main Frame\n :return:\n '
panel = wx.Panel(self)
hbox = wx.BoxSizer(wx.HORIZONTAL)
fgs = wx.FlexGridSizer(5, 2, 10, 10)
hostname_label = wx.StaticText(panel, label='Hostname:')
self.hostname_choice = wx.ComboBox(panel, choices=self.hostnames, style=(wx.CB_READONLY | wx.CB_DROPDOWN))
self.Bind(wx.EVT_COMBOBOX_DROPDOWN, self.update_hostnames_handler, self.hostname_choice)
data_label = wx.StaticText(panel, label='Data:')
self.data_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
send_btn = wx.Button(panel, label='Send')
self.Bind(wx.EVT_BUTTON, self._send_data_handler, send_btn)
clear_btn = wx.Button(panel, label='Clear')
self.Bind(wx.EVT_BUTTON, self._clear_handler, clear_btn)
message = wx.StaticText(panel, label='Message')
self.message_text = wx.TextCtrl(panel, value=, style=(wx.TE_READONLY | wx.TE_MULTILINE))
log = wx.StaticText(panel, label='Log')
self.log_text = wx.TextCtrl(panel, value=, style=(wx.TE_READONLY | wx.TE_MULTILINE))
fgs.AddMany([hostname_label, (self.hostname_choice, 1, wx.EXPAND), (data_label, 1, wx.EXPAND), (self.data_text, 1, wx.EXPAND), (clear_btn, 1, wx.EXPAND), (send_btn, 1, wx.EXPAND), (message, 1, wx.EXPAND), (self.message_text, 1, wx.EXPAND), (log, 1, wx.EXPAND), (self.log_text, 1, wx.EXPAND)])
fgs.AddGrowableRow(1, 1)
fgs.AddGrowableRow(3, 1)
fgs.AddGrowableRow(4, 1)
fgs.AddGrowableCol(1, 1)
hbox.Add(fgs, proportion=2, flag=(wx.ALL | wx.EXPAND), border=15)
panel.SetSizer(hbox)
|
def init_main(self):
'\n Init Main Frame\n :return:\n '
panel = wx.Panel(self)
hbox = wx.BoxSizer(wx.HORIZONTAL)
fgs = wx.FlexGridSizer(5, 2, 10, 10)
hostname_label = wx.StaticText(panel, label='Hostname:')
self.hostname_choice = wx.ComboBox(panel, choices=self.hostnames, style=(wx.CB_READONLY | wx.CB_DROPDOWN))
self.Bind(wx.EVT_COMBOBOX_DROPDOWN, self.update_hostnames_handler, self.hostname_choice)
data_label = wx.StaticText(panel, label='Data:')
self.data_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
send_btn = wx.Button(panel, label='Send')
self.Bind(wx.EVT_BUTTON, self._send_data_handler, send_btn)
clear_btn = wx.Button(panel, label='Clear')
self.Bind(wx.EVT_BUTTON, self._clear_handler, clear_btn)
message = wx.StaticText(panel, label='Message')
self.message_text = wx.TextCtrl(panel, value=, style=(wx.TE_READONLY | wx.TE_MULTILINE))
log = wx.StaticText(panel, label='Log')
self.log_text = wx.TextCtrl(panel, value=, style=(wx.TE_READONLY | wx.TE_MULTILINE))
fgs.AddMany([hostname_label, (self.hostname_choice, 1, wx.EXPAND), (data_label, 1, wx.EXPAND), (self.data_text, 1, wx.EXPAND), (clear_btn, 1, wx.EXPAND), (send_btn, 1, wx.EXPAND), (message, 1, wx.EXPAND), (self.message_text, 1, wx.EXPAND), (log, 1, wx.EXPAND), (self.log_text, 1, wx.EXPAND)])
fgs.AddGrowableRow(1, 1)
fgs.AddGrowableRow(3, 1)
fgs.AddGrowableRow(4, 1)
fgs.AddGrowableCol(1, 1)
hbox.Add(fgs, proportion=2, flag=(wx.ALL | wx.EXPAND), border=15)
panel.SetSizer(hbox)<|docstring|>Init Main Frame
:return:<|endoftext|>
|
46c02ae5935c996afd78393c1292706c80f1212bfad502119be0b10c0d91ccaf
|
@click.command()
@click.option('-n', '--accession_number', help='Accession number (object number in TMS exports)')
@click.option('-e', '--environment', default='local', help='Environment.')
@click.option('--input', type=click.File('r'), required=False)
@click.option('--dryrun', is_flag=True, help='Dry run, nothing is actually changed.')
def extract(environment, dryrun, accession_number=None, input=None):
'Query MS SQL TMS database and updates MySQL collection website database.'
with open('config.yaml', 'r') as f:
config = yaml.load(f)
if ((not accession_number) and (not input)):
click.echo('Nothing to process. Pass an accession number or input file\n')
exit()
accession_numbers = []
if accession_number:
accession_numbers.append(accession_number)
elif input:
for accession_number in input:
accession_numbers.append(accession_number.rstrip())
count = 0
for accession_number in accession_numbers:
count += 1
click.echo('===========================================================\n')
click.echo('{count} - Running for {accession_number} on {environment}\n'.format(count=count, accession_number=accession_number, environment=environment))
conn = pymssql.connect(config[environment]['mssql']['host'], config[environment]['mssql']['username'], config[environment]['mssql']['password'], config[environment]['mssql']['database'])
cursor = conn.cursor()
tms_query = "SELECT TOP 1\n o.ObjectNumber,\n o.ObjectName,\n ot.Title,\n o.Description,\n o.DateBegin,\n o.DateEnd,\n o.Dated,\n o.CreditLine,\n o.ClassificationID,\n o.Medium,\n o.Dimensions,\n o.Markings,\n o.Signed,\n o.Inscribed,\n o.Provenance,\n o.PublicAccess,\n o.Accountability,\n o.ObjectID,\n can.AltNameId,\n can.DisplayName,\n c.ConstituentID,\n cxrd.ConXrefID\n FROM Objects o\n INNER JOIN ObjTitles ot ON o.ObjectID = ot.ObjectID AND ot.DisplayOrder = 1\n INNER JOIN ConXrefs cxr ON cxr.ID = o.ObjectID\n INNER JOIN ConXrefDetails cxrd ON cxr.ConXrefID = cxrd.ConXrefID\n INNER JOIN Roles r ON cxr.RoleID = r.RoleID\n INNER JOIN ConAltNames can ON cxrd.NameID = can.AltNameId\n INNER JOIN Constituents c ON can.ConstituentID = c.ConstituentID\n WHERE\n (cxr.TableID = 108) AND\n (r.Role = 'Designer' OR r.role='Artist') AND\n (r.RoleTypeID = 1) AND\n (cxrd.UnMasked=0) AND\n (o.ObjectNumber = '{accession_number}')".format(accession_number=accession_number)
cursor.execute(tms_query)
for row in cursor:
tms_object = {'object_number': row[0], 'name': row[1], 'title': row[2], 'description': (row[3] if row[3] else ''), 'date_begin': row[4], 'date_end': row[5], 'dated': (row[6] if row[6] else ''), 'credit': row[7], 'classification_id': row[8], 'medium': (row[9] if row[9] else ''), 'dimensions': (row[10] if row[10] else ''), 'markings': (row[11] if row[11] else ''), 'signed': (row[12] if row[12] else ''), 'inscribed': (row[13] if row[13] else ''), 'provenance': (row[14] if row[14] else ''), 'public_access': row[15], 'accountability': row[16], 'display_name': row[19], 'constituent_id': row[20], 'conxref_id': row[21]}
break
if dryrun:
click.echo('\nDry run MS SQL Server...\n')
click.echo(tms_object)
conn.close()
db = MySQLdb.connect(host=config[environment]['mysql']['host'], user=config[environment]['mysql']['username'], passwd=config[environment]['mysql']['password'], db=config[environment]['mysql']['database'], use_unicode=True, charset='utf8')
c = db.cursor()
c.execute(("SELECT id, accession_number FROM Objects WHERE accession_number = '%s'" % (accession_number,)))
row = c.fetchone()
object_id = row[0]
if ('local' == environment):
url = 'https://collection.cooperhewitt.test/objects/{object_id}/'.format(object_id=object_id)
elif ('production' == environment):
url = 'https://collection.cooperhewitt.org/objects/{object_id}/'.format(object_id=object_id)
click.echo('Object URL: {url}\n'.format(url=url))
if dryrun:
click.echo('\nDry run MySQL...\n')
click.echo(row)
else:
click.echo(tms_object)
c.execute(('UPDATE Objects SET titles="{""1"":{""en-uk"":""%s""}}", display_medium="%s", tms_extras=\'{"display_date":"%s","markings":"%s","signed":"%s","inscribed":"%s","provenance":"%s","description":"%s","dimensions":"%s","name":"%s","credit":"%s","public_access":"%s","accountability":"%s"}\' WHERE accession_number = \'%s\'' % (tms_object['title'].replace("'", "''"), tms_object['medium'].replace("'", "''"), tms_object['dated'], tms_object['markings'].replace("'", "''"), tms_object['signed'].replace("'", "''"), tms_object['inscribed'].replace("'", "''"), tms_object['provenance'].replace("'", "''"), tms_object['description'].replace("'", "''"), tms_object['dimensions'], tms_object['name'].replace("'", "''"), tms_object['credit'].replace("'", "''"), tms_object['public_access'], tms_object['accountability'], accession_number)))
if (5840 == tms_object['constituent_id']):
c.execute(('INSERT INTO ObjectsPeople (object_id, person_id, role_id, alt_name_tms_id, is_public, object_score, role_type_id, parent_id, count_images, count_images_public, tms_id) VALUES (\n %d, 18050457, 35236565, 8383, 1, 7, 1, 0, 1, 1, %d) ON DUPLICATE KEY UPDATE object_id = %d' % (object_id, tms_object['conxref_id'], object_id)))
db.commit()
db.close()
click.echo('===========================================================\n')
|
Query MS SQL TMS database and updates MySQL collection website database.
|
python-extract/extract.py
|
extract
|
alexisbellido/ansible-and-docker
| 0
|
python
|
@click.command()
@click.option('-n', '--accession_number', help='Accession number (object number in TMS exports)')
@click.option('-e', '--environment', default='local', help='Environment.')
@click.option('--input', type=click.File('r'), required=False)
@click.option('--dryrun', is_flag=True, help='Dry run, nothing is actually changed.')
def extract(environment, dryrun, accession_number=None, input=None):
with open('config.yaml', 'r') as f:
config = yaml.load(f)
if ((not accession_number) and (not input)):
click.echo('Nothing to process. Pass an accession number or input file\n')
exit()
accession_numbers = []
if accession_number:
accession_numbers.append(accession_number)
elif input:
for accession_number in input:
accession_numbers.append(accession_number.rstrip())
count = 0
for accession_number in accession_numbers:
count += 1
click.echo('===========================================================\n')
click.echo('{count} - Running for {accession_number} on {environment}\n'.format(count=count, accession_number=accession_number, environment=environment))
conn = pymssql.connect(config[environment]['mssql']['host'], config[environment]['mssql']['username'], config[environment]['mssql']['password'], config[environment]['mssql']['database'])
cursor = conn.cursor()
tms_query = "SELECT TOP 1\n o.ObjectNumber,\n o.ObjectName,\n ot.Title,\n o.Description,\n o.DateBegin,\n o.DateEnd,\n o.Dated,\n o.CreditLine,\n o.ClassificationID,\n o.Medium,\n o.Dimensions,\n o.Markings,\n o.Signed,\n o.Inscribed,\n o.Provenance,\n o.PublicAccess,\n o.Accountability,\n o.ObjectID,\n can.AltNameId,\n can.DisplayName,\n c.ConstituentID,\n cxrd.ConXrefID\n FROM Objects o\n INNER JOIN ObjTitles ot ON o.ObjectID = ot.ObjectID AND ot.DisplayOrder = 1\n INNER JOIN ConXrefs cxr ON cxr.ID = o.ObjectID\n INNER JOIN ConXrefDetails cxrd ON cxr.ConXrefID = cxrd.ConXrefID\n INNER JOIN Roles r ON cxr.RoleID = r.RoleID\n INNER JOIN ConAltNames can ON cxrd.NameID = can.AltNameId\n INNER JOIN Constituents c ON can.ConstituentID = c.ConstituentID\n WHERE\n (cxr.TableID = 108) AND\n (r.Role = 'Designer' OR r.role='Artist') AND\n (r.RoleTypeID = 1) AND\n (cxrd.UnMasked=0) AND\n (o.ObjectNumber = '{accession_number}')".format(accession_number=accession_number)
cursor.execute(tms_query)
for row in cursor:
tms_object = {'object_number': row[0], 'name': row[1], 'title': row[2], 'description': (row[3] if row[3] else ), 'date_begin': row[4], 'date_end': row[5], 'dated': (row[6] if row[6] else ), 'credit': row[7], 'classification_id': row[8], 'medium': (row[9] if row[9] else ), 'dimensions': (row[10] if row[10] else ), 'markings': (row[11] if row[11] else ), 'signed': (row[12] if row[12] else ), 'inscribed': (row[13] if row[13] else ), 'provenance': (row[14] if row[14] else ), 'public_access': row[15], 'accountability': row[16], 'display_name': row[19], 'constituent_id': row[20], 'conxref_id': row[21]}
break
if dryrun:
click.echo('\nDry run MS SQL Server...\n')
click.echo(tms_object)
conn.close()
db = MySQLdb.connect(host=config[environment]['mysql']['host'], user=config[environment]['mysql']['username'], passwd=config[environment]['mysql']['password'], db=config[environment]['mysql']['database'], use_unicode=True, charset='utf8')
c = db.cursor()
c.execute(("SELECT id, accession_number FROM Objects WHERE accession_number = '%s'" % (accession_number,)))
row = c.fetchone()
object_id = row[0]
if ('local' == environment):
url = 'https://collection.cooperhewitt.test/objects/{object_id}/'.format(object_id=object_id)
elif ('production' == environment):
url = 'https://collection.cooperhewitt.org/objects/{object_id}/'.format(object_id=object_id)
click.echo('Object URL: {url}\n'.format(url=url))
if dryrun:
click.echo('\nDry run MySQL...\n')
click.echo(row)
else:
click.echo(tms_object)
c.execute(('UPDATE Objects SET titles="{1:{en-uk:%s}}", display_medium="%s", tms_extras=\'{"display_date":"%s","markings":"%s","signed":"%s","inscribed":"%s","provenance":"%s","description":"%s","dimensions":"%s","name":"%s","credit":"%s","public_access":"%s","accountability":"%s"}\' WHERE accession_number = \'%s\ % (tms_object['title'].replace("'", ), tms_object['medium'].replace("'", ), tms_object['dated'], tms_object['markings'].replace("'", ), tms_object['signed'].replace("'", ), tms_object['inscribed'].replace("'", ), tms_object['provenance'].replace("'", ), tms_object['description'].replace("'", ), tms_object['dimensions'], tms_object['name'].replace("'", ), tms_object['credit'].replace("'", ), tms_object['public_access'], tms_object['accountability'], accession_number)))
if (5840 == tms_object['constituent_id']):
c.execute(('INSERT INTO ObjectsPeople (object_id, person_id, role_id, alt_name_tms_id, is_public, object_score, role_type_id, parent_id, count_images, count_images_public, tms_id) VALUES (\n %d, 18050457, 35236565, 8383, 1, 7, 1, 0, 1, 1, %d) ON DUPLICATE KEY UPDATE object_id = %d' % (object_id, tms_object['conxref_id'], object_id)))
db.commit()
db.close()
click.echo('===========================================================\n')
|
@click.command()
@click.option('-n', '--accession_number', help='Accession number (object number in TMS exports)')
@click.option('-e', '--environment', default='local', help='Environment.')
@click.option('--input', type=click.File('r'), required=False)
@click.option('--dryrun', is_flag=True, help='Dry run, nothing is actually changed.')
def extract(environment, dryrun, accession_number=None, input=None):
with open('config.yaml', 'r') as f:
config = yaml.load(f)
if ((not accession_number) and (not input)):
click.echo('Nothing to process. Pass an accession number or input file\n')
exit()
accession_numbers = []
if accession_number:
accession_numbers.append(accession_number)
elif input:
for accession_number in input:
accession_numbers.append(accession_number.rstrip())
count = 0
for accession_number in accession_numbers:
count += 1
click.echo('===========================================================\n')
click.echo('{count} - Running for {accession_number} on {environment}\n'.format(count=count, accession_number=accession_number, environment=environment))
conn = pymssql.connect(config[environment]['mssql']['host'], config[environment]['mssql']['username'], config[environment]['mssql']['password'], config[environment]['mssql']['database'])
cursor = conn.cursor()
tms_query = "SELECT TOP 1\n o.ObjectNumber,\n o.ObjectName,\n ot.Title,\n o.Description,\n o.DateBegin,\n o.DateEnd,\n o.Dated,\n o.CreditLine,\n o.ClassificationID,\n o.Medium,\n o.Dimensions,\n o.Markings,\n o.Signed,\n o.Inscribed,\n o.Provenance,\n o.PublicAccess,\n o.Accountability,\n o.ObjectID,\n can.AltNameId,\n can.DisplayName,\n c.ConstituentID,\n cxrd.ConXrefID\n FROM Objects o\n INNER JOIN ObjTitles ot ON o.ObjectID = ot.ObjectID AND ot.DisplayOrder = 1\n INNER JOIN ConXrefs cxr ON cxr.ID = o.ObjectID\n INNER JOIN ConXrefDetails cxrd ON cxr.ConXrefID = cxrd.ConXrefID\n INNER JOIN Roles r ON cxr.RoleID = r.RoleID\n INNER JOIN ConAltNames can ON cxrd.NameID = can.AltNameId\n INNER JOIN Constituents c ON can.ConstituentID = c.ConstituentID\n WHERE\n (cxr.TableID = 108) AND\n (r.Role = 'Designer' OR r.role='Artist') AND\n (r.RoleTypeID = 1) AND\n (cxrd.UnMasked=0) AND\n (o.ObjectNumber = '{accession_number}')".format(accession_number=accession_number)
cursor.execute(tms_query)
for row in cursor:
tms_object = {'object_number': row[0], 'name': row[1], 'title': row[2], 'description': (row[3] if row[3] else ), 'date_begin': row[4], 'date_end': row[5], 'dated': (row[6] if row[6] else ), 'credit': row[7], 'classification_id': row[8], 'medium': (row[9] if row[9] else ), 'dimensions': (row[10] if row[10] else ), 'markings': (row[11] if row[11] else ), 'signed': (row[12] if row[12] else ), 'inscribed': (row[13] if row[13] else ), 'provenance': (row[14] if row[14] else ), 'public_access': row[15], 'accountability': row[16], 'display_name': row[19], 'constituent_id': row[20], 'conxref_id': row[21]}
break
if dryrun:
click.echo('\nDry run MS SQL Server...\n')
click.echo(tms_object)
conn.close()
db = MySQLdb.connect(host=config[environment]['mysql']['host'], user=config[environment]['mysql']['username'], passwd=config[environment]['mysql']['password'], db=config[environment]['mysql']['database'], use_unicode=True, charset='utf8')
c = db.cursor()
c.execute(("SELECT id, accession_number FROM Objects WHERE accession_number = '%s'" % (accession_number,)))
row = c.fetchone()
object_id = row[0]
if ('local' == environment):
url = 'https://collection.cooperhewitt.test/objects/{object_id}/'.format(object_id=object_id)
elif ('production' == environment):
url = 'https://collection.cooperhewitt.org/objects/{object_id}/'.format(object_id=object_id)
click.echo('Object URL: {url}\n'.format(url=url))
if dryrun:
click.echo('\nDry run MySQL...\n')
click.echo(row)
else:
click.echo(tms_object)
c.execute(('UPDATE Objects SET titles="{1:{en-uk:%s}}", display_medium="%s", tms_extras=\'{"display_date":"%s","markings":"%s","signed":"%s","inscribed":"%s","provenance":"%s","description":"%s","dimensions":"%s","name":"%s","credit":"%s","public_access":"%s","accountability":"%s"}\' WHERE accession_number = \'%s\ % (tms_object['title'].replace("'", ), tms_object['medium'].replace("'", ), tms_object['dated'], tms_object['markings'].replace("'", ), tms_object['signed'].replace("'", ), tms_object['inscribed'].replace("'", ), tms_object['provenance'].replace("'", ), tms_object['description'].replace("'", ), tms_object['dimensions'], tms_object['name'].replace("'", ), tms_object['credit'].replace("'", ), tms_object['public_access'], tms_object['accountability'], accession_number)))
if (5840 == tms_object['constituent_id']):
c.execute(('INSERT INTO ObjectsPeople (object_id, person_id, role_id, alt_name_tms_id, is_public, object_score, role_type_id, parent_id, count_images, count_images_public, tms_id) VALUES (\n %d, 18050457, 35236565, 8383, 1, 7, 1, 0, 1, 1, %d) ON DUPLICATE KEY UPDATE object_id = %d' % (object_id, tms_object['conxref_id'], object_id)))
db.commit()
db.close()
click.echo('===========================================================\n')<|docstring|>Query MS SQL TMS database and updates MySQL collection website database.<|endoftext|>
|
3069f4d3fcc9588c3f06e3fb9753ba96669aa7ec91ccae23ec29909d36192a0b
|
def test_create_error_report(self):
'Integration test for the ErrorReportsAPI.create_error_report method.'
pass
|
Integration test for the ErrorReportsAPI.create_error_report method.
|
py3canvas/tests/error_reports.py
|
test_create_error_report
|
tylerclair/py3canvas
| 0
|
python
|
def test_create_error_report(self):
pass
|
def test_create_error_report(self):
pass<|docstring|>Integration test for the ErrorReportsAPI.create_error_report method.<|endoftext|>
|
63973664d6777fcc6993a0d8e218ff68325eb84bc686dec26cd839704fa67f60
|
def secure_http_response(func):
'\n A decorator to remove server header information\n '
@wraps(func)
def __wrapper(*args, **kwargs):
response = func(*args, **kwargs)
response.headers['server'] = ''
return response
return __wrapper
|
A decorator to remove server header information
|
src/modules/listen_server.py
|
secure_http_response
|
mehrdad-shokri/macro_pack
| 1,550
|
python
|
def secure_http_response(func):
'\n \n '
@wraps(func)
def __wrapper(*args, **kwargs):
response = func(*args, **kwargs)
response.headers['server'] =
return response
return __wrapper
|
def secure_http_response(func):
'\n \n '
@wraps(func)
def __wrapper(*args, **kwargs):
response = func(*args, **kwargs)
response.headers['server'] =
return response
return __wrapper<|docstring|>A decorator to remove server header information<|endoftext|>
|
a1f321b9acfa4fbe4da900b9ed6caf052275274b92275b7028e009ca521e0051
|
@webapp.route('/q', methods=['GET', 'POST'])
@secure_http_response
def query():
' called by client to ask for instruction '
clientId = request.form['id']
pendingInstruction = input((' %s >> ' % clientId))
return make_response(pendingInstruction)
|
called by client to ask for instruction
|
src/modules/listen_server.py
|
query
|
mehrdad-shokri/macro_pack
| 1,550
|
python
|
@webapp.route('/q', methods=['GET', 'POST'])
@secure_http_response
def query():
' '
clientId = request.form['id']
pendingInstruction = input((' %s >> ' % clientId))
return make_response(pendingInstruction)
|
@webapp.route('/q', methods=['GET', 'POST'])
@secure_http_response
def query():
' '
clientId = request.form['id']
pendingInstruction = input((' %s >> ' % clientId))
return make_response(pendingInstruction)<|docstring|>called by client to ask for instruction<|endoftext|>
|
d307cdb04a0debc02a7e68b560fce6fb0903f551bb0e2fc4f6a995dbcf6d3dd9
|
@webapp.route('/h', methods=['GET', 'POST'])
@secure_http_response
def hello():
' called by client when signalling itself'
clientId = request.form['id']
ip = request.remote_addr
logging.info((' [-] Hello from %s. - IP: %s' % (clientId, ip)))
return make_response('OK')
|
called by client when signalling itself
|
src/modules/listen_server.py
|
hello
|
mehrdad-shokri/macro_pack
| 1,550
|
python
|
@webapp.route('/h', methods=['GET', 'POST'])
@secure_http_response
def hello():
' '
clientId = request.form['id']
ip = request.remote_addr
logging.info((' [-] Hello from %s. - IP: %s' % (clientId, ip)))
return make_response('OK')
|
@webapp.route('/h', methods=['GET', 'POST'])
@secure_http_response
def hello():
' '
clientId = request.form['id']
ip = request.remote_addr
logging.info((' [-] Hello from %s. - IP: %s' % (clientId, ip)))
return make_response('OK')<|docstring|>called by client when signalling itself<|endoftext|>
|
4f5f0bc56ba75d99276974eff9d6cca5c855db02361f816f1f77d3b1584767ff
|
@webapp.route('/a', methods=['GET', 'POST'])
@secure_http_response
def answer():
' called by client when responding to command '
cmdOutput = request.form['cmdOutput']
logging.info((' %s \n ' % cmdOutput))
return make_response('OK')
|
called by client when responding to command
|
src/modules/listen_server.py
|
answer
|
mehrdad-shokri/macro_pack
| 1,550
|
python
|
@webapp.route('/a', methods=['GET', 'POST'])
@secure_http_response
def answer():
' '
cmdOutput = request.form['cmdOutput']
logging.info((' %s \n ' % cmdOutput))
return make_response('OK')
|
@webapp.route('/a', methods=['GET', 'POST'])
@secure_http_response
def answer():
' '
cmdOutput = request.form['cmdOutput']
logging.info((' %s \n ' % cmdOutput))
return make_response('OK')<|docstring|>called by client when responding to command<|endoftext|>
|
a2e8c92d14fe58cc589de9bbda16c8af9ee665cb23c5f49429efca840858e497
|
def run(self):
' Starts listening server'
logging.info(' [+] Starting Macro_Pack web server...')
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
logging.info(((' [-] Files in "' + self.listenRoot) + '" folder are accessible using http://{ip}:{port}/u/'.format(ip=getHostIp(), port=self.listenPort)))
logging.info((' [-] Listening on port %s (ctrl-c to exit)...' % self.listenPort))
webapp.run(host='0.0.0.0', port=int(self.listenPort))
|
Starts listening server
|
src/modules/listen_server.py
|
run
|
mehrdad-shokri/macro_pack
| 1,550
|
python
|
def run(self):
' '
logging.info(' [+] Starting Macro_Pack web server...')
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
logging.info(((' [-] Files in "' + self.listenRoot) + '" folder are accessible using http://{ip}:{port}/u/'.format(ip=getHostIp(), port=self.listenPort)))
logging.info((' [-] Listening on port %s (ctrl-c to exit)...' % self.listenPort))
webapp.run(host='0.0.0.0', port=int(self.listenPort))
|
def run(self):
' '
logging.info(' [+] Starting Macro_Pack web server...')
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
logging.info(((' [-] Files in "' + self.listenRoot) + '" folder are accessible using http://{ip}:{port}/u/'.format(ip=getHostIp(), port=self.listenPort)))
logging.info((' [-] Listening on port %s (ctrl-c to exit)...' % self.listenPort))
webapp.run(host='0.0.0.0', port=int(self.listenPort))<|docstring|>Starts listening server<|endoftext|>
|
8eb187f27e31341c9a0dc9be00579506345917254ae4a1a4b537ab3da6fc6542
|
def addcountries():
'Add country list from csv file'
with open('install/iso_3166_2_countries.csv') as csvfile:
data = csv.reader(csvfile, delimiter=',')
data = list(data)
for r in data[2:]:
country = Country.query.filter_by(cc=r[10]).first()
if (country is None):
country = Country(cc=r[10], name=r[1])
db.session.add(country)
db.session.commit()
|
Add country list from csv file
|
app/fixtures/testfixture.py
|
addcountries
|
davewood/do-portal
| 0
|
python
|
def addcountries():
with open('install/iso_3166_2_countries.csv') as csvfile:
data = csv.reader(csvfile, delimiter=',')
data = list(data)
for r in data[2:]:
country = Country.query.filter_by(cc=r[10]).first()
if (country is None):
country = Country(cc=r[10], name=r[1])
db.session.add(country)
db.session.commit()
|
def addcountries():
with open('install/iso_3166_2_countries.csv') as csvfile:
data = csv.reader(csvfile, delimiter=',')
data = list(data)
for r in data[2:]:
country = Country.query.filter_by(cc=r[10]).first()
if (country is None):
country = Country(cc=r[10], name=r[1])
db.session.add(country)
db.session.commit()<|docstring|>Add country list from csv file<|endoftext|>
|
156e36e871690a937c66ef5a5d1f5216d6e786276a9740efd18f554adcaa7457
|
def addyaml(yamlfile='install/testdata.yaml'):
'Add sample data from yaml file'
with open(yamlfile, 'r') as stream:
data_loaded = yaml.load(stream)
for org in data_loaded['org']:
if ('full_name' not in org):
org['full_name'] = org['abbreviation']
if ('display_name' not in org):
org['display_name'] = org['abbreviation']
o = Organization(abbreviation=org['abbreviation'], full_name=org['full_name'], display_name=org['display_name'])
if ('parent_org' in org):
po = Organization.query.filter_by(abbreviation=org['parent_org']).first()
o.parent_org = po
db.session.add(o)
db.session.commit()
for user in data_loaded['user']:
u = User.query.filter_by(name=user['name']).first()
if (not u):
u = User(name=user['name'])
u.email = user['email']
u.api_key = u.generate_api_key()
if ('password' in user):
u.password = user['password']
else:
u.password = 'Bla12345%'
db.session.add(u)
role = MembershipRole.query.filter_by(name=user['role']).first()
org = Organization.query.filter_by(abbreviation=user['org']).first()
if ('email' not in user):
user['email'] = 'example@example.com'
if ('street' not in user):
user['street'] = 'no street'
if ('zip' not in user):
user['zip'] = '1234'
if ('city' not in user):
user['city'] = 'n/a'
if ('country' not in user):
country_o = Country.query.filter_by(cc='AT').first()
else:
country_o = Country.query.filter_by(cc=user['country']).first()
if ('comment' not in user):
user['comment'] = 'no comment'
if ('phone' not in user):
user['phone'] = '+12345678'
if ('mobile' not in user):
user['mobile'] = '+33456788'
if ('sms_alerting' not in user):
user['sms_alerting'] = 0
oxu = OrganizationMembership(email=user['email'], street=user['street'], city=user['city'], zip=user['zip'], country=country_o, comment=user['comment'], phone=user['phone'], mobile=user['mobile'], organization=org, user=u, membership_role=role, sms_alerting=user['sms_alerting'])
db.session.commit()
|
Add sample data from yaml file
|
app/fixtures/testfixture.py
|
addyaml
|
davewood/do-portal
| 0
|
python
|
def addyaml(yamlfile='install/testdata.yaml'):
with open(yamlfile, 'r') as stream:
data_loaded = yaml.load(stream)
for org in data_loaded['org']:
if ('full_name' not in org):
org['full_name'] = org['abbreviation']
if ('display_name' not in org):
org['display_name'] = org['abbreviation']
o = Organization(abbreviation=org['abbreviation'], full_name=org['full_name'], display_name=org['display_name'])
if ('parent_org' in org):
po = Organization.query.filter_by(abbreviation=org['parent_org']).first()
o.parent_org = po
db.session.add(o)
db.session.commit()
for user in data_loaded['user']:
u = User.query.filter_by(name=user['name']).first()
if (not u):
u = User(name=user['name'])
u.email = user['email']
u.api_key = u.generate_api_key()
if ('password' in user):
u.password = user['password']
else:
u.password = 'Bla12345%'
db.session.add(u)
role = MembershipRole.query.filter_by(name=user['role']).first()
org = Organization.query.filter_by(abbreviation=user['org']).first()
if ('email' not in user):
user['email'] = 'example@example.com'
if ('street' not in user):
user['street'] = 'no street'
if ('zip' not in user):
user['zip'] = '1234'
if ('city' not in user):
user['city'] = 'n/a'
if ('country' not in user):
country_o = Country.query.filter_by(cc='AT').first()
else:
country_o = Country.query.filter_by(cc=user['country']).first()
if ('comment' not in user):
user['comment'] = 'no comment'
if ('phone' not in user):
user['phone'] = '+12345678'
if ('mobile' not in user):
user['mobile'] = '+33456788'
if ('sms_alerting' not in user):
user['sms_alerting'] = 0
oxu = OrganizationMembership(email=user['email'], street=user['street'], city=user['city'], zip=user['zip'], country=country_o, comment=user['comment'], phone=user['phone'], mobile=user['mobile'], organization=org, user=u, membership_role=role, sms_alerting=user['sms_alerting'])
db.session.commit()
|
def addyaml(yamlfile='install/testdata.yaml'):
with open(yamlfile, 'r') as stream:
data_loaded = yaml.load(stream)
for org in data_loaded['org']:
if ('full_name' not in org):
org['full_name'] = org['abbreviation']
if ('display_name' not in org):
org['display_name'] = org['abbreviation']
o = Organization(abbreviation=org['abbreviation'], full_name=org['full_name'], display_name=org['display_name'])
if ('parent_org' in org):
po = Organization.query.filter_by(abbreviation=org['parent_org']).first()
o.parent_org = po
db.session.add(o)
db.session.commit()
for user in data_loaded['user']:
u = User.query.filter_by(name=user['name']).first()
if (not u):
u = User(name=user['name'])
u.email = user['email']
u.api_key = u.generate_api_key()
if ('password' in user):
u.password = user['password']
else:
u.password = 'Bla12345%'
db.session.add(u)
role = MembershipRole.query.filter_by(name=user['role']).first()
org = Organization.query.filter_by(abbreviation=user['org']).first()
if ('email' not in user):
user['email'] = 'example@example.com'
if ('street' not in user):
user['street'] = 'no street'
if ('zip' not in user):
user['zip'] = '1234'
if ('city' not in user):
user['city'] = 'n/a'
if ('country' not in user):
country_o = Country.query.filter_by(cc='AT').first()
else:
country_o = Country.query.filter_by(cc=user['country']).first()
if ('comment' not in user):
user['comment'] = 'no comment'
if ('phone' not in user):
user['phone'] = '+12345678'
if ('mobile' not in user):
user['mobile'] = '+33456788'
if ('sms_alerting' not in user):
user['sms_alerting'] = 0
oxu = OrganizationMembership(email=user['email'], street=user['street'], city=user['city'], zip=user['zip'], country=country_o, comment=user['comment'], phone=user['phone'], mobile=user['mobile'], organization=org, user=u, membership_role=role, sms_alerting=user['sms_alerting'])
db.session.commit()<|docstring|>Add sample data from yaml file<|endoftext|>
|
ab0daf9edadf29095760dcac9fbe53cc16dd1fb963681e84b5b09a02537e8ac6
|
def print():
'output sample data'
u = User.query.filter_by(name='certmaster').first()
echo((u.name + str(u.id)))
for uo in u.user_memberships:
print(uo.email)
print(uo)
print(uo.organization.full_name)
for co in uo.organization.child_organizations:
print(co.full_name)
print('**** organization_memberships ******')
for oxu in u.get_organization_memberships():
print(('%s %s %s' % (oxu.email, oxu.membership_role.name, oxu.organization.full_name)))
print('**** organization_memberships ******')
oms = User.query.filter_by(name='EnergyOrg Admin').first().get_organization_memberships()
if oms:
for oxu in oms:
print(('%s %s %s' % (oxu.email, oxu.membership_role.name, oxu.organization.full_name)))
print('**** organizations ******')
orgs = u.get_organizations()
i = 0
for org in orgs:
print(('%d %s %s' % (i, org.full_name, org.abbreviation)))
i += 1
print('**** permission checks ******')
eorg_user = User.query.filter_by(name='E-Org User').first()
eorgmaster = User.query.filter_by(name='eorgmaster').first()
print(('eorgmaster for E-Org %s \nE-Org for eorgmaster %s' % (eorgmaster.may_handle_user(eorg_user), eorg_user.may_handle_user(eorgmaster))))
print(('cert for E-Org %s \nE-Org for cert %s' % (u.may_handle_user(eorg_user), eorg_user.may_handle_user(u))))
print(('cert for eorgmaster %s \neorgmaster for cert %s' % (u.may_handle_user(eorgmaster), eorgmaster.may_handle_user(u))))
print('**** user.get_userss ******')
users = u.get_users()
for user in users:
print(('%s' % user.name))
print('**** user.get_users(eorgmaster) ******')
users = eorgmaster.get_users()
for user in users:
print(('%s' % user.name))
|
output sample data
|
app/fixtures/testfixture.py
|
print
|
davewood/do-portal
| 0
|
python
|
def print():
u = User.query.filter_by(name='certmaster').first()
echo((u.name + str(u.id)))
for uo in u.user_memberships:
print(uo.email)
print(uo)
print(uo.organization.full_name)
for co in uo.organization.child_organizations:
print(co.full_name)
print('**** organization_memberships ******')
for oxu in u.get_organization_memberships():
print(('%s %s %s' % (oxu.email, oxu.membership_role.name, oxu.organization.full_name)))
print('**** organization_memberships ******')
oms = User.query.filter_by(name='EnergyOrg Admin').first().get_organization_memberships()
if oms:
for oxu in oms:
print(('%s %s %s' % (oxu.email, oxu.membership_role.name, oxu.organization.full_name)))
print('**** organizations ******')
orgs = u.get_organizations()
i = 0
for org in orgs:
print(('%d %s %s' % (i, org.full_name, org.abbreviation)))
i += 1
print('**** permission checks ******')
eorg_user = User.query.filter_by(name='E-Org User').first()
eorgmaster = User.query.filter_by(name='eorgmaster').first()
print(('eorgmaster for E-Org %s \nE-Org for eorgmaster %s' % (eorgmaster.may_handle_user(eorg_user), eorg_user.may_handle_user(eorgmaster))))
print(('cert for E-Org %s \nE-Org for cert %s' % (u.may_handle_user(eorg_user), eorg_user.may_handle_user(u))))
print(('cert for eorgmaster %s \neorgmaster for cert %s' % (u.may_handle_user(eorgmaster), eorgmaster.may_handle_user(u))))
print('**** user.get_userss ******')
users = u.get_users()
for user in users:
print(('%s' % user.name))
print('**** user.get_users(eorgmaster) ******')
users = eorgmaster.get_users()
for user in users:
print(('%s' % user.name))
|
def print():
u = User.query.filter_by(name='certmaster').first()
echo((u.name + str(u.id)))
for uo in u.user_memberships:
print(uo.email)
print(uo)
print(uo.organization.full_name)
for co in uo.organization.child_organizations:
print(co.full_name)
print('**** organization_memberships ******')
for oxu in u.get_organization_memberships():
print(('%s %s %s' % (oxu.email, oxu.membership_role.name, oxu.organization.full_name)))
print('**** organization_memberships ******')
oms = User.query.filter_by(name='EnergyOrg Admin').first().get_organization_memberships()
if oms:
for oxu in oms:
print(('%s %s %s' % (oxu.email, oxu.membership_role.name, oxu.organization.full_name)))
print('**** organizations ******')
orgs = u.get_organizations()
i = 0
for org in orgs:
print(('%d %s %s' % (i, org.full_name, org.abbreviation)))
i += 1
print('**** permission checks ******')
eorg_user = User.query.filter_by(name='E-Org User').first()
eorgmaster = User.query.filter_by(name='eorgmaster').first()
print(('eorgmaster for E-Org %s \nE-Org for eorgmaster %s' % (eorgmaster.may_handle_user(eorg_user), eorg_user.may_handle_user(eorgmaster))))
print(('cert for E-Org %s \nE-Org for cert %s' % (u.may_handle_user(eorg_user), eorg_user.may_handle_user(u))))
print(('cert for eorgmaster %s \neorgmaster for cert %s' % (u.may_handle_user(eorgmaster), eorgmaster.may_handle_user(u))))
print('**** user.get_userss ******')
users = u.get_users()
for user in users:
print(('%s' % user.name))
print('**** user.get_users(eorgmaster) ******')
users = eorgmaster.get_users()
for user in users:
print(('%s' % user.name))<|docstring|>output sample data<|endoftext|>
|
20524255c826b41bff194eda5da747d706b9b3bec7fb28c7b9cf2672226e2af7
|
def get_uppermost_dir(cwd: Path) -> Path:
'Returns the root directory.\n Example: `C:\\` fow windows, `/` for Linux.\n '
cur_path = cwd.parent
parent = cur_path.parent
while (cur_path != parent):
(cur_path, parent) = (cur_path.parent, parent.parent)
return cur_path
|
Returns the root directory.
Example: `C:\` fow windows, `/` for Linux.
|
Swit/common/paths.py
|
get_uppermost_dir
|
NogaOs/wit
| 0
|
python
|
def get_uppermost_dir(cwd: Path) -> Path:
'Returns the root directory.\n Example: `C:\\` fow windows, `/` for Linux.\n '
cur_path = cwd.parent
parent = cur_path.parent
while (cur_path != parent):
(cur_path, parent) = (cur_path.parent, parent.parent)
return cur_path
|
def get_uppermost_dir(cwd: Path) -> Path:
'Returns the root directory.\n Example: `C:\\` fow windows, `/` for Linux.\n '
cur_path = cwd.parent
parent = cur_path.parent
while (cur_path != parent):
(cur_path, parent) = (cur_path.parent, parent.parent)
return cur_path<|docstring|>Returns the root directory.
Example: `C:\` fow windows, `/` for Linux.<|endoftext|>
|
44a945f8818bc7a965e5f533f218b68e73707a86d1d7d2d7ad943967811b4700
|
def get_repo_path(cwd: Path) -> Path:
'Starting from the current working directory, moves up the tree until it finds a directory\n containing a `.swit` directory. That dir shall be referenced to as the repository.\n '
uppermost_dir = get_uppermost_dir(cwd)
while (cwd != uppermost_dir):
for dir_name in cwd.glob('*.swit'):
if dir_name:
return cwd
cwd = cwd.parent
raise WitDirectoryNotFoundError("No `.swit` directory found. Please make sure you're set to the correct cwd, or create a repository using the `init()` method.")
|
Starting from the current working directory, moves up the tree until it finds a directory
containing a `.swit` directory. That dir shall be referenced to as the repository.
|
Swit/common/paths.py
|
get_repo_path
|
NogaOs/wit
| 0
|
python
|
def get_repo_path(cwd: Path) -> Path:
'Starting from the current working directory, moves up the tree until it finds a directory\n containing a `.swit` directory. That dir shall be referenced to as the repository.\n '
uppermost_dir = get_uppermost_dir(cwd)
while (cwd != uppermost_dir):
for dir_name in cwd.glob('*.swit'):
if dir_name:
return cwd
cwd = cwd.parent
raise WitDirectoryNotFoundError("No `.swit` directory found. Please make sure you're set to the correct cwd, or create a repository using the `init()` method.")
|
def get_repo_path(cwd: Path) -> Path:
'Starting from the current working directory, moves up the tree until it finds a directory\n containing a `.swit` directory. That dir shall be referenced to as the repository.\n '
uppermost_dir = get_uppermost_dir(cwd)
while (cwd != uppermost_dir):
for dir_name in cwd.glob('*.swit'):
if dir_name:
return cwd
cwd = cwd.parent
raise WitDirectoryNotFoundError("No `.swit` directory found. Please make sure you're set to the correct cwd, or create a repository using the `init()` method.")<|docstring|>Starting from the current working directory, moves up the tree until it finds a directory
containing a `.swit` directory. That dir shall be referenced to as the repository.<|endoftext|>
|
dfbe40b2235c69eec29ba003205ea6c892a86cc9b7bfdf5918c0ed5678582e7a
|
def invitation_tickets_change_stream_get(self, **kwargs):
'\n Create a change stream.\n \n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.invitation_tickets_change_stream_get(callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param str options: \n :return: file\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.invitation_tickets_change_stream_get_with_http_info(**kwargs)
else:
data = self.invitation_tickets_change_stream_get_with_http_info(**kwargs)
return data
|
Create a change stream.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.invitation_tickets_change_stream_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str options:
:return: file
If the method is called asynchronously,
returns the request thread.
|
TweakApi/apis/invitation_ticket_api.py
|
invitation_tickets_change_stream_get
|
tweak-com-public/tweak-api-client-python
| 0
|
python
|
def invitation_tickets_change_stream_get(self, **kwargs):
'\n Create a change stream.\n \n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.invitation_tickets_change_stream_get(callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param str options: \n :return: file\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.invitation_tickets_change_stream_get_with_http_info(**kwargs)
else:
data = self.invitation_tickets_change_stream_get_with_http_info(**kwargs)
return data
|
def invitation_tickets_change_stream_get(self, **kwargs):
'\n Create a change stream.\n \n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.invitation_tickets_change_stream_get(callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param str options: \n :return: file\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.invitation_tickets_change_stream_get_with_http_info(**kwargs)
else:
data = self.invitation_tickets_change_stream_get_with_http_info(**kwargs)
return data<|docstring|>Create a change stream.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.invitation_tickets_change_stream_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str options:
:return: file
If the method is called asynchronously,
returns the request thread.<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.