partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
SdpRelaxation.find_solution_ranks
Helper function to detect rank loop in the solution matrix. :param sdpRelaxation: The SDP relaxation. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param x_mat: Optional parameter providing the primal solution of the moment matrix. If not provided, the solution ...
ncpol2sdpa/sdp_relaxation.py
def find_solution_ranks(self, xmat=None, baselevel=0): """Helper function to detect rank loop in the solution matrix. :param sdpRelaxation: The SDP relaxation. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param x_mat: Optional parameter providing the primal solution of the ...
def find_solution_ranks(self, xmat=None, baselevel=0): """Helper function to detect rank loop in the solution matrix. :param sdpRelaxation: The SDP relaxation. :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`. :param x_mat: Optional parameter providing the primal solution of the ...
[ "Helper", "function", "to", "detect", "rank", "loop", "in", "the", "solution", "matrix", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1167-L1183
[ "def", "find_solution_ranks", "(", "self", ",", "xmat", "=", "None", ",", "baselevel", "=", "0", ")", ":", "return", "find_solution_ranks", "(", "self", ",", "xmat", "=", "xmat", ",", "baselevel", "=", "baselevel", ")" ]
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
SdpRelaxation.get_dual
Given a solution of the dual problem and a constraint of any type, it returns the corresponding block in the dual solution. If it is an equality constraint that was converted to a pair of inequalities, it returns a two-tuple of the matching dual blocks. :param constraint: The constraint...
ncpol2sdpa/sdp_relaxation.py
def get_dual(self, constraint, ymat=None): """Given a solution of the dual problem and a constraint of any type, it returns the corresponding block in the dual solution. If it is an equality constraint that was converted to a pair of inequalities, it returns a two-tuple of the matching d...
def get_dual(self, constraint, ymat=None): """Given a solution of the dual problem and a constraint of any type, it returns the corresponding block in the dual solution. If it is an equality constraint that was converted to a pair of inequalities, it returns a two-tuple of the matching d...
[ "Given", "a", "solution", "of", "the", "dual", "problem", "and", "a", "constraint", "of", "any", "type", "it", "returns", "the", "corresponding", "block", "in", "the", "dual", "solution", ".", "If", "it", "is", "an", "equality", "constraint", "that", "was"...
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1185-L1212
[ "def", "get_dual", "(", "self", ",", "constraint", ",", "ymat", "=", "None", ")", ":", "if", "not", "isinstance", "(", "constraint", ",", "Expr", ")", ":", "raise", "Exception", "(", "\"Not a monomial or polynomial!\"", ")", "elif", "self", ".", "status", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
SdpRelaxation.write_to_file
Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek or .csv for human readable format. :type filename: str. :param filetype: Optiona...
ncpol2sdpa/sdp_relaxation.py
def write_to_file(self, filename, filetype=None): """Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek or .csv for human readable format. ...
def write_to_file(self, filename, filetype=None): """Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek or .csv for human readable format. ...
[ "Write", "the", "relaxation", "to", "a", "file", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1214-L1247
[ "def", "write_to_file", "(", "self", ",", "filename", ",", "filetype", "=", "None", ")", ":", "if", "filetype", "==", "\"sdpa\"", "and", "not", "filename", ".", "endswith", "(", "\".dat-s\"", ")", ":", "raise", "Exception", "(", "\"SDPA files must have .dat-s ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
SdpRelaxation.get_relaxation
Get the SDP relaxation of a noncommutative polynomial optimization problem. :param level: The level of the relaxation. The value -1 will skip automatic monomial generation and use only the monomials supplied by the option `extramonomials`. :type level...
ncpol2sdpa/sdp_relaxation.py
def get_relaxation(self, level, objective=None, inequalities=None, equalities=None, substitutions=None, momentinequalities=None, momentequalities=None, momentsubstitutions=None, removeequalities=False, extramonomials=None, ...
def get_relaxation(self, level, objective=None, inequalities=None, equalities=None, substitutions=None, momentinequalities=None, momentequalities=None, momentsubstitutions=None, removeequalities=False, extramonomials=None, ...
[ "Get", "the", "SDP", "relaxation", "of", "a", "noncommutative", "polynomial", "optimization", "problem", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1290-L1434
[ "def", "get_relaxation", "(", "self", ",", "level", ",", "objective", "=", "None", ",", "inequalities", "=", "None", ",", "equalities", "=", "None", ",", "substitutions", "=", "None", ",", "momentinequalities", "=", "None", ",", "momentequalities", "=", "Non...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
flatten
Flatten a list of lists to a list. :param lol: A list of lists in arbitrary depth. :type lol: list of list. :returns: flat list of elements.
ncpol2sdpa/nc_utils.py
def flatten(lol): """Flatten a list of lists to a list. :param lol: A list of lists in arbitrary depth. :type lol: list of list. :returns: flat list of elements. """ new_list = [] for element in lol: if element is None: continue elif not isinstance(element, list...
def flatten(lol): """Flatten a list of lists to a list. :param lol: A list of lists in arbitrary depth. :type lol: list of list. :returns: flat list of elements. """ new_list = [] for element in lol: if element is None: continue elif not isinstance(element, list...
[ "Flatten", "a", "list", "of", "lists", "to", "a", "list", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L16-L32
[ "def", "flatten", "(", "lol", ")", ":", "new_list", "=", "[", "]", "for", "element", "in", "lol", ":", "if", "element", "is", "None", ":", "continue", "elif", "not", "isinstance", "(", "element", ",", "list", ")", "and", "not", "isinstance", "(", "el...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
simplify_polynomial
Simplify a polynomial for uniform handling later.
ncpol2sdpa/nc_utils.py
def simplify_polynomial(polynomial, monomial_substitutions): """Simplify a polynomial for uniform handling later. """ if isinstance(polynomial, (int, float, complex)): return polynomial polynomial = (1.0 * polynomial).expand(mul=True, multinomial=True) ...
def simplify_polynomial(polynomial, monomial_substitutions): """Simplify a polynomial for uniform handling later. """ if isinstance(polynomial, (int, float, complex)): return polynomial polynomial = (1.0 * polynomial).expand(mul=True, multinomial=True) ...
[ "Simplify", "a", "polynomial", "for", "uniform", "handling", "later", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L35-L54
[ "def", "simplify_polynomial", "(", "polynomial", ",", "monomial_substitutions", ")", ":", "if", "isinstance", "(", "polynomial", ",", "(", "int", ",", "float", ",", "complex", ")", ")", ":", "return", "polynomial", "polynomial", "=", "(", "1.0", "*", "polyno...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
__separate_scalar_factor
Separate the constant factor from a monomial.
ncpol2sdpa/nc_utils.py
def __separate_scalar_factor(monomial): """Separate the constant factor from a monomial. """ scalar_factor = 1 if is_number_type(monomial): return S.One, monomial if monomial == 0: return S.One, 0 comm_factors, _ = split_commutative_parts(monomial) if len(comm_factors) > 0: ...
def __separate_scalar_factor(monomial): """Separate the constant factor from a monomial. """ scalar_factor = 1 if is_number_type(monomial): return S.One, monomial if monomial == 0: return S.One, 0 comm_factors, _ = split_commutative_parts(monomial) if len(comm_factors) > 0: ...
[ "Separate", "the", "constant", "factor", "from", "a", "monomial", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L81-L96
[ "def", "__separate_scalar_factor", "(", "monomial", ")", ":", "scalar_factor", "=", "1", "if", "is_number_type", "(", "monomial", ")", ":", "return", "S", ".", "One", ",", "monomial", "if", "monomial", "==", "0", ":", "return", "S", ".", "One", ",", "0",...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
get_support
Gets the support of a polynomial.
ncpol2sdpa/nc_utils.py
def get_support(variables, polynomial): """Gets the support of a polynomial. """ support = [] if is_number_type(polynomial): support.append([0] * len(variables)) return support for monomial in polynomial.expand().as_coefficients_dict(): tmp_support = [0] * len(variables) ...
def get_support(variables, polynomial): """Gets the support of a polynomial. """ support = [] if is_number_type(polynomial): support.append([0] * len(variables)) return support for monomial in polynomial.expand().as_coefficients_dict(): tmp_support = [0] * len(variables) ...
[ "Gets", "the", "support", "of", "a", "polynomial", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L99-L121
[ "def", "get_support", "(", "variables", ",", "polynomial", ")", ":", "support", "=", "[", "]", "if", "is_number_type", "(", "polynomial", ")", ":", "support", ".", "append", "(", "[", "0", "]", "*", "len", "(", "variables", ")", ")", "return", "support...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
get_support_variables
Gets the support of a polynomial.
ncpol2sdpa/nc_utils.py
def get_support_variables(polynomial): """Gets the support of a polynomial. """ support = [] if is_number_type(polynomial): return support for monomial in polynomial.expand().as_coefficients_dict(): mon, _ = __separate_scalar_factor(monomial) symbolic_support = flatten(split_...
def get_support_variables(polynomial): """Gets the support of a polynomial. """ support = [] if is_number_type(polynomial): return support for monomial in polynomial.expand().as_coefficients_dict(): mon, _ = __separate_scalar_factor(monomial) symbolic_support = flatten(split_...
[ "Gets", "the", "support", "of", "a", "polynomial", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L124-L143
[ "def", "get_support_variables", "(", "polynomial", ")", ":", "support", "=", "[", "]", "if", "is_number_type", "(", "polynomial", ")", ":", "return", "support", "for", "monomial", "in", "polynomial", ".", "expand", "(", ")", ".", "as_coefficients_dict", "(", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
separate_scalar_factor
Construct a monomial with the coefficient separated from an element in a polynomial.
ncpol2sdpa/nc_utils.py
def separate_scalar_factor(element): """Construct a monomial with the coefficient separated from an element in a polynomial. """ coeff = 1.0 monomial = S.One if isinstance(element, (int, float, complex)): coeff *= element return monomial, coeff for var in element.as_coeff_mul...
def separate_scalar_factor(element): """Construct a monomial with the coefficient separated from an element in a polynomial. """ coeff = 1.0 monomial = S.One if isinstance(element, (int, float, complex)): coeff *= element return monomial, coeff for var in element.as_coeff_mul...
[ "Construct", "a", "monomial", "with", "the", "coefficient", "separated", "from", "an", "element", "in", "a", "polynomial", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L146-L165
[ "def", "separate_scalar_factor", "(", "element", ")", ":", "coeff", "=", "1.0", "monomial", "=", "S", ".", "One", "if", "isinstance", "(", "element", ",", "(", "int", ",", "float", ",", "complex", ")", ")", ":", "coeff", "*=", "element", "return", "mon...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
count_ncmonomials
Given a list of monomials, it counts those that have a certain degree, or less. The function is useful when certain monomials were eliminated from the basis. :param variables: The noncommutative variables making up the monomials :param monomials: List of monomials (the monomial basis). :param degre...
ncpol2sdpa/nc_utils.py
def count_ncmonomials(monomials, degree): """Given a list of monomials, it counts those that have a certain degree, or less. The function is useful when certain monomials were eliminated from the basis. :param variables: The noncommutative variables making up the monomials :param monomials: List of...
def count_ncmonomials(monomials, degree): """Given a list of monomials, it counts those that have a certain degree, or less. The function is useful when certain monomials were eliminated from the basis. :param variables: The noncommutative variables making up the monomials :param monomials: List of...
[ "Given", "a", "list", "of", "monomials", "it", "counts", "those", "that", "have", "a", "certain", "degree", "or", "less", ".", "The", "function", "is", "useful", "when", "certain", "monomials", "were", "eliminated", "from", "the", "basis", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L168-L185
[ "def", "count_ncmonomials", "(", "monomials", ",", "degree", ")", ":", "ncmoncount", "=", "0", "for", "monomial", "in", "monomials", ":", "if", "ncdegree", "(", "monomial", ")", "<=", "degree", ":", "ncmoncount", "+=", "1", "else", ":", "break", "return", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
apply_substitutions
Helper function to remove monomials from the basis.
ncpol2sdpa/nc_utils.py
def apply_substitutions(monomial, monomial_substitutions, pure=False): """Helper function to remove monomials from the basis.""" if is_number_type(monomial): return monomial original_monomial = monomial changed = True if not pure: substitutions = monomial_substitutions else: ...
def apply_substitutions(monomial, monomial_substitutions, pure=False): """Helper function to remove monomials from the basis.""" if is_number_type(monomial): return monomial original_monomial = monomial changed = True if not pure: substitutions = monomial_substitutions else: ...
[ "Helper", "function", "to", "remove", "monomials", "from", "the", "basis", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L188-L214
[ "def", "apply_substitutions", "(", "monomial", ",", "monomial_substitutions", ",", "pure", "=", "False", ")", ":", "if", "is_number_type", "(", "monomial", ")", ":", "return", "monomial", "original_monomial", "=", "monomial", "changed", "=", "True", "if", "not",...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
fast_substitute
Experimental fast substitution routine that considers only restricted cases of noncommutative algebras. In rare cases, it fails to find a substitution. Use it with proper testing. :param monomial: The monomial with parts need to be substituted. :param old_sub: The part to be replaced. :param new_su...
ncpol2sdpa/nc_utils.py
def fast_substitute(monomial, old_sub, new_sub): """Experimental fast substitution routine that considers only restricted cases of noncommutative algebras. In rare cases, it fails to find a substitution. Use it with proper testing. :param monomial: The monomial with parts need to be substituted. :p...
def fast_substitute(monomial, old_sub, new_sub): """Experimental fast substitution routine that considers only restricted cases of noncommutative algebras. In rare cases, it fails to find a substitution. Use it with proper testing. :param monomial: The monomial with parts need to be substituted. :p...
[ "Experimental", "fast", "substitution", "routine", "that", "considers", "only", "restricted", "cases", "of", "noncommutative", "algebras", ".", "In", "rare", "cases", "it", "fails", "to", "find", "a", "substitution", ".", "Use", "it", "with", "proper", "testing"...
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L217-L352
[ "def", "fast_substitute", "(", "monomial", ",", "old_sub", ",", "new_sub", ")", ":", "if", "is_number_type", "(", "monomial", ")", ":", "return", "monomial", "if", "monomial", ".", "is_Add", ":", "return", "sum", "(", "[", "fast_substitute", "(", "element", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
generate_variables
Generates a number of commutative or noncommutative variables :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1 if n_vars > 1. :type name: str. :param n_vars: The number of variables. ...
ncpol2sdpa/nc_utils.py
def generate_variables(name, n_vars=1, hermitian=None, commutative=True): """Generates a number of commutative or noncommutative variables :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1...
def generate_variables(name, n_vars=1, hermitian=None, commutative=True): """Generates a number of commutative or noncommutative variables :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1...
[ "Generates", "a", "number", "of", "commutative", "or", "noncommutative", "variables" ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L355-L395
[ "def", "generate_variables", "(", "name", ",", "n_vars", "=", "1", ",", "hermitian", "=", "None", ",", "commutative", "=", "True", ")", ":", "variables", "=", "[", "]", "for", "i", "in", "range", "(", "n_vars", ")", ":", "if", "n_vars", ">", "1", "...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
generate_operators
Generates a number of commutative or noncommutative operators :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-1 if n_vars > 1. :type name: str. :param n_vars: The number of variables. ...
ncpol2sdpa/nc_utils.py
def generate_operators(name, n_vars=1, hermitian=None, commutative=False): """Generates a number of commutative or noncommutative operators :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-...
def generate_operators(name, n_vars=1, hermitian=None, commutative=False): """Generates a number of commutative or noncommutative operators :param name: The prefix in the symbolic representation of the noncommuting variables. This will be suffixed by a number from 0 to n_vars-...
[ "Generates", "a", "number", "of", "commutative", "or", "noncommutative", "operators" ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L398-L434
[ "def", "generate_operators", "(", "name", ",", "n_vars", "=", "1", ",", "hermitian", "=", "None", ",", "commutative", "=", "False", ")", ":", "variables", "=", "[", "]", "for", "i", "in", "range", "(", "n_vars", ")", ":", "if", "n_vars", ">", "1", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
get_monomials
Generates all noncommutative monomials up to a degree :param variables: The noncommutative variables to generate monomials from :type variables: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physics.quantum.operator.HermitianOperator`. :...
ncpol2sdpa/nc_utils.py
def get_monomials(variables, degree): """Generates all noncommutative monomials up to a degree :param variables: The noncommutative variables to generate monomials from :type variables: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physi...
def get_monomials(variables, degree): """Generates all noncommutative monomials up to a degree :param variables: The noncommutative variables to generate monomials from :type variables: list of :class:`sympy.physics.quantum.operator.Operator` or :class:`sympy.physi...
[ "Generates", "all", "noncommutative", "monomials", "up", "to", "a", "degree" ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L437-L469
[ "def", "get_monomials", "(", "variables", ",", "degree", ")", ":", "if", "degree", "==", "-", "1", ":", "return", "[", "]", "if", "not", "variables", ":", "return", "[", "S", ".", "One", "]", "else", ":", "_variables", "=", "variables", "[", ":", "...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
ncdegree
Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial.
ncpol2sdpa/nc_utils.py
def ncdegree(polynomial): """Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial. """ degree = 0 if is_number_type(polynomial): ret...
def ncdegree(polynomial): """Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial. """ degree = 0 if is_number_type(polynomial): ret...
[ "Returns", "the", "degree", "of", "a", "noncommutative", "polynomial", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L472-L493
[ "def", "ncdegree", "(", "polynomial", ")", ":", "degree", "=", "0", "if", "is_number_type", "(", "polynomial", ")", ":", "return", "degree", "polynomial", "=", "polynomial", ".", "expand", "(", ")", "for", "monomial", "in", "polynomial", ".", "as_coefficient...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
iscomplex
Returns whether the polynomial has complex coefficients :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: bool -- whether there is a complex coefficient.
ncpol2sdpa/nc_utils.py
def iscomplex(polynomial): """Returns whether the polynomial has complex coefficients :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: bool -- whether there is a complex coefficient. """ if isinstance(polynomial, (int, float)):...
def iscomplex(polynomial): """Returns whether the polynomial has complex coefficients :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: bool -- whether there is a complex coefficient. """ if isinstance(polynomial, (int, float)):...
[ "Returns", "whether", "the", "polynomial", "has", "complex", "coefficients" ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L496-L513
[ "def", "iscomplex", "(", "polynomial", ")", ":", "if", "isinstance", "(", "polynomial", ",", "(", "int", ",", "float", ")", ")", ":", "return", "False", "if", "isinstance", "(", "polynomial", ",", "complex", ")", ":", "return", "True", "polynomial", "=",...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
get_all_monomials
Return the monomials of a certain degree.
ncpol2sdpa/nc_utils.py
def get_all_monomials(variables, extramonomials, substitutions, degree, removesubstitutions=True): """Return the monomials of a certain degree. """ monomials = get_monomials(variables, degree) if extramonomials is not None: monomials.extend(extramonomials) if removesubs...
def get_all_monomials(variables, extramonomials, substitutions, degree, removesubstitutions=True): """Return the monomials of a certain degree. """ monomials = get_monomials(variables, degree) if extramonomials is not None: monomials.extend(extramonomials) if removesubs...
[ "Return", "the", "monomials", "of", "a", "certain", "degree", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L516-L530
[ "def", "get_all_monomials", "(", "variables", ",", "extramonomials", ",", "substitutions", ",", "degree", ",", "removesubstitutions", "=", "True", ")", ":", "monomials", "=", "get_monomials", "(", "variables", ",", "degree", ")", "if", "extramonomials", "is", "n...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
pick_monomials_up_to_degree
Collect monomials up to a given degree.
ncpol2sdpa/nc_utils.py
def pick_monomials_up_to_degree(monomials, degree): """Collect monomials up to a given degree. """ ordered_monomials = [] if degree >= 0: ordered_monomials.append(S.One) for deg in range(1, degree + 1): ordered_monomials.extend(pick_monomials_of_degree(monomials, deg)) return ord...
def pick_monomials_up_to_degree(monomials, degree): """Collect monomials up to a given degree. """ ordered_monomials = [] if degree >= 0: ordered_monomials.append(S.One) for deg in range(1, degree + 1): ordered_monomials.extend(pick_monomials_of_degree(monomials, deg)) return ord...
[ "Collect", "monomials", "up", "to", "a", "given", "degree", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L533-L541
[ "def", "pick_monomials_up_to_degree", "(", "monomials", ",", "degree", ")", ":", "ordered_monomials", "=", "[", "]", "if", "degree", ">=", "0", ":", "ordered_monomials", ".", "append", "(", "S", ".", "One", ")", "for", "deg", "in", "range", "(", "1", ","...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
pick_monomials_of_degree
Collect all monomials up of a given degree.
ncpol2sdpa/nc_utils.py
def pick_monomials_of_degree(monomials, degree): """Collect all monomials up of a given degree. """ selected_monomials = [] for monomial in monomials: if ncdegree(monomial) == degree: selected_monomials.append(monomial) return selected_monomials
def pick_monomials_of_degree(monomials, degree): """Collect all monomials up of a given degree. """ selected_monomials = [] for monomial in monomials: if ncdegree(monomial) == degree: selected_monomials.append(monomial) return selected_monomials
[ "Collect", "all", "monomials", "up", "of", "a", "given", "degree", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L544-L551
[ "def", "pick_monomials_of_degree", "(", "monomials", ",", "degree", ")", ":", "selected_monomials", "=", "[", "]", "for", "monomial", "in", "monomials", ":", "if", "ncdegree", "(", "monomial", ")", "==", "degree", ":", "selected_monomials", ".", "append", "(",...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
save_monomial_index
Save a monomial dictionary for debugging purposes. :param filename: The name of the file to save to. :type filename: str. :param monomial_index: The monomial index of the SDP relaxation. :type monomial_index: dict of :class:`sympy.core.expr.Expr`.
ncpol2sdpa/nc_utils.py
def save_monomial_index(filename, monomial_index): """Save a monomial dictionary for debugging purposes. :param filename: The name of the file to save to. :type filename: str. :param monomial_index: The monomial index of the SDP relaxation. :type monomial_index: dict of :class:`sympy.core.expr.Expr...
def save_monomial_index(filename, monomial_index): """Save a monomial dictionary for debugging purposes. :param filename: The name of the file to save to. :type filename: str. :param monomial_index: The monomial index of the SDP relaxation. :type monomial_index: dict of :class:`sympy.core.expr.Expr...
[ "Save", "a", "monomial", "dictionary", "for", "debugging", "purposes", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L562-L577
[ "def", "save_monomial_index", "(", "filename", ",", "monomial_index", ")", ":", "monomial_translation", "=", "[", "''", "]", "*", "(", "len", "(", "monomial_index", ")", "+", "1", ")", "for", "key", ",", "k", "in", "monomial_index", ".", "items", "(", ")...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
unique
Helper function to include only unique monomials in a basis.
ncpol2sdpa/nc_utils.py
def unique(seq): """Helper function to include only unique monomials in a basis.""" seen = {} result = [] for item in seq: marker = item if marker in seen: continue seen[marker] = 1 result.append(item) return result
def unique(seq): """Helper function to include only unique monomials in a basis.""" seen = {} result = [] for item in seq: marker = item if marker in seen: continue seen[marker] = 1 result.append(item) return result
[ "Helper", "function", "to", "include", "only", "unique", "monomials", "in", "a", "basis", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L580-L590
[ "def", "unique", "(", "seq", ")", ":", "seen", "=", "{", "}", "result", "=", "[", "]", "for", "item", "in", "seq", ":", "marker", "=", "item", "if", "marker", "in", "seen", ":", "continue", "seen", "[", "marker", "]", "=", "1", "result", ".", "...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
build_permutation_matrix
Build a permutation matrix for a permutation.
ncpol2sdpa/nc_utils.py
def build_permutation_matrix(permutation): """Build a permutation matrix for a permutation. """ matrix = lil_matrix((len(permutation), len(permutation))) column = 0 for row in permutation: matrix[row, column] = 1 column += 1 return matrix
def build_permutation_matrix(permutation): """Build a permutation matrix for a permutation. """ matrix = lil_matrix((len(permutation), len(permutation))) column = 0 for row in permutation: matrix[row, column] = 1 column += 1 return matrix
[ "Build", "a", "permutation", "matrix", "for", "a", "permutation", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L593-L601
[ "def", "build_permutation_matrix", "(", "permutation", ")", ":", "matrix", "=", "lil_matrix", "(", "(", "len", "(", "permutation", ")", ",", "len", "(", "permutation", ")", ")", ")", "column", "=", "0", "for", "row", "in", "permutation", ":", "matrix", "...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
convert_relational
Convert all inequalities to >=0 form.
ncpol2sdpa/nc_utils.py
def convert_relational(relational): """Convert all inequalities to >=0 form. """ rel = relational.rel_op if rel in ['==', '>=', '>']: return relational.lhs-relational.rhs elif rel in ['<=', '<']: return relational.rhs-relational.lhs else: raise Exception("The relational o...
def convert_relational(relational): """Convert all inequalities to >=0 form. """ rel = relational.rel_op if rel in ['==', '>=', '>']: return relational.lhs-relational.rhs elif rel in ['<=', '<']: return relational.rhs-relational.lhs else: raise Exception("The relational o...
[ "Convert", "all", "inequalities", "to", ">", "=", "0", "form", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L604-L614
[ "def", "convert_relational", "(", "relational", ")", ":", "rel", "=", "relational", ".", "rel_op", "if", "rel", "in", "[", "'=='", ",", "'>='", ",", "'>'", "]", ":", "return", "relational", ".", "lhs", "-", "relational", ".", "rhs", "elif", "rel", "in"...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
value
Returns the value of a board >>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']] >>> value(b) 1 >>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']] >>> value(b) -1 >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', '...
examples/tictactoeexample.py
def value(board, who='x'): """Returns the value of a board >>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']] >>> value(b) 1 >>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']] >>> value(b) -1 >>> b = Board(); b._rows = [['x', 'o', '...
def value(board, who='x'): """Returns the value of a board >>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']] >>> value(b) 1 >>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']] >>> value(b) -1 >>> b = Board(); b._rows = [['x', 'o', '...
[ "Returns", "the", "value", "of", "a", "board", ">>>", "b", "=", "Board", "()", ";", "b", ".", "_rows", "=", "[[", "x", "x", "x", "]", "[", "x", "x", "x", "]", "[", "x", "x", "x", "]]", ">>>", "value", "(", "b", ")", "1", ">>>", "b", "=", ...
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L68-L94
[ "def", "value", "(", "board", ",", "who", "=", "'x'", ")", ":", "w", "=", "board", ".", "winner", "(", ")", "if", "w", "==", "who", ":", "return", "1", "if", "w", "==", "opp", "(", "who", ")", ":", "return", "-", "1", "if", "board", ".", "t...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
ai
Returns best next board >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']] >>> ai(b) < Board |xo.xo.x..| >
examples/tictactoeexample.py
def ai(board, who='x'): """ Returns best next board >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']] >>> ai(b) < Board |xo.xo.x..| > """ return sorted(board.possible(), key=lambda b: value(b, who))[-1]
def ai(board, who='x'): """ Returns best next board >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']] >>> ai(b) < Board |xo.xo.x..| > """ return sorted(board.possible(), key=lambda b: value(b, who))[-1]
[ "Returns", "best", "next", "board" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L96-L104
[ "def", "ai", "(", "board", ",", "who", "=", "'x'", ")", ":", "return", "sorted", "(", "board", ".", "possible", "(", ")", ",", "key", "=", "lambda", "b", ":", "value", "(", "b", ",", "who", ")", ")", "[", "-", "1", "]" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
Board.winner
Returns either x or o if one of them won, otherwise None
examples/tictactoeexample.py
def winner(self): """Returns either x or o if one of them won, otherwise None""" for c in 'xo': for comb in [(0,3,6), (1,4,7), (2,5,8), (0,1,2), (3,4,5), (6,7,8), (0,4,8), (2,4,6)]: if all(self.spots[p] == c for p in comb): return c return None
def winner(self): """Returns either x or o if one of them won, otherwise None""" for c in 'xo': for comb in [(0,3,6), (1,4,7), (2,5,8), (0,1,2), (3,4,5), (6,7,8), (0,4,8), (2,4,6)]: if all(self.spots[p] == c for p in comb): return c return None
[ "Returns", "either", "x", "or", "o", "if", "one", "of", "them", "won", "otherwise", "None" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L40-L46
[ "def", "winner", "(", "self", ")", ":", "for", "c", "in", "'xo'", ":", "for", "comb", "in", "[", "(", "0", ",", "3", ",", "6", ")", ",", "(", "1", ",", "4", ",", "7", ")", ",", "(", "2", ",", "5", ",", "8", ")", ",", "(", "0", ",", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FaacetsRelaxation.get_relaxation
Get the sparse SDP relaxation of a Bell inequality. :param A_configuration: The definition of measurements of Alice. :type A_configuration: list of list of int. :param B_configuration: The definition of measurements of Bob. :type B_configuration: list of list of int. :param I: T...
ncpol2sdpa/faacets_relaxation.py
def get_relaxation(self, A_configuration, B_configuration, I): """Get the sparse SDP relaxation of a Bell inequality. :param A_configuration: The definition of measurements of Alice. :type A_configuration: list of list of int. :param B_configuration: The definition of measurements of Bo...
def get_relaxation(self, A_configuration, B_configuration, I): """Get the sparse SDP relaxation of a Bell inequality. :param A_configuration: The definition of measurements of Alice. :type A_configuration: list of list of int. :param B_configuration: The definition of measurements of Bo...
[ "Get", "the", "sparse", "SDP", "relaxation", "of", "a", "Bell", "inequality", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/faacets_relaxation.py#L63-L91
[ "def", "get_relaxation", "(", "self", ",", "A_configuration", ",", "B_configuration", ",", "I", ")", ":", "coefficients", "=", "collinsgisin_to_faacets", "(", "I", ")", "M", ",", "ncIndices", "=", "get_faacets_moment_matrix", "(", "A_configuration", ",", "B_config...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
share
Returns list of users track has been shared with. Either track or url need to be provided.
soundcloud_cli/api/share.py
def share(track_id=None, url=None, users=None): """ Returns list of users track has been shared with. Either track or url need to be provided. """ client = get_client() if url: track_id = client.get('/resolve', url=url).id if not users: return client.get('/tracks/%d/permis...
def share(track_id=None, url=None, users=None): """ Returns list of users track has been shared with. Either track or url need to be provided. """ client = get_client() if url: track_id = client.get('/resolve', url=url).id if not users: return client.get('/tracks/%d/permis...
[ "Returns", "list", "of", "users", "track", "has", "been", "shared", "with", ".", "Either", "track", "or", "url", "need", "to", "be", "provided", "." ]
zeekay/soundcloud-cli
python
https://github.com/zeekay/soundcloud-cli/blob/8a83013683e1acf32f093239bbb6d3c02bc50b37/soundcloud_cli/api/share.py#L7-L34
[ "def", "share", "(", "track_id", "=", "None", ",", "url", "=", "None", ",", "users", "=", "None", ")", ":", "client", "=", "get_client", "(", ")", "if", "url", ":", "track_id", "=", "client", ".", "get", "(", "'/resolve'", ",", "url", "=", "url", ...
8a83013683e1acf32f093239bbb6d3c02bc50b37
train
solve_with_cvxopt
Helper function to convert the SDP problem to PICOS and call CVXOPT solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`.
ncpol2sdpa/picos_utils.py
def solve_with_cvxopt(sdp, solverparameters=None): """Helper function to convert the SDP problem to PICOS and call CVXOPT solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. """ P = convert_to_picos(sdp) P.set_option("solver", "cvxo...
def solve_with_cvxopt(sdp, solverparameters=None): """Helper function to convert the SDP problem to PICOS and call CVXOPT solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. """ P = convert_to_picos(sdp) P.set_option("solver", "cvxo...
[ "Helper", "function", "to", "convert", "the", "SDP", "problem", "to", "PICOS", "and", "call", "CVXOPT", "solver", "and", "parse", "the", "output", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/picos_utils.py#L13-L34
[ "def", "solve_with_cvxopt", "(", "sdp", ",", "solverparameters", "=", "None", ")", ":", "P", "=", "convert_to_picos", "(", "sdp", ")", "P", ".", "set_option", "(", "\"solver\"", ",", "\"cvxopt\"", ")", "P", ".", "set_option", "(", "\"verbose\"", ",", "sdp"...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
convert_to_picos
Convert an SDP relaxation to a PICOS problem such that the exported .dat-s file is extremely sparse, there is not penalty imposed in terms of SDP variables or number of constraints. This conversion can be used for imposing extra constraints on the moment matrix, such as partial transpose. :param sdp: T...
ncpol2sdpa/picos_utils.py
def convert_to_picos(sdp, duplicate_moment_matrix=False): """Convert an SDP relaxation to a PICOS problem such that the exported .dat-s file is extremely sparse, there is not penalty imposed in terms of SDP variables or number of constraints. This conversion can be used for imposing extra constraints on...
def convert_to_picos(sdp, duplicate_moment_matrix=False): """Convert an SDP relaxation to a PICOS problem such that the exported .dat-s file is extremely sparse, there is not penalty imposed in terms of SDP variables or number of constraints. This conversion can be used for imposing extra constraints on...
[ "Convert", "an", "SDP", "relaxation", "to", "a", "PICOS", "problem", "such", "that", "the", "exported", ".", "dat", "-", "s", "file", "is", "extremely", "sparse", "there", "is", "not", "penalty", "imposed", "in", "terms", "of", "SDP", "variables", "or", ...
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/picos_utils.py#L37-L125
[ "def", "convert_to_picos", "(", "sdp", ",", "duplicate_moment_matrix", "=", "False", ")", ":", "import", "picos", "as", "pic", "import", "cvxopt", "as", "cvx", "P", "=", "pic", ".", "Problem", "(", "verbose", "=", "sdp", ".", "verbose", ")", "block_size", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
solve_with_cvxpy
Helper function to convert the SDP problem to CVXPY and call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`.
ncpol2sdpa/cvxpy_utils.py
def solve_with_cvxpy(sdp, solverparameters=None): """Helper function to convert the SDP problem to CVXPY and call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. """ problem = convert_to_cvxpy(sdp) if solverparameters is not...
def solve_with_cvxpy(sdp, solverparameters=None): """Helper function to convert the SDP problem to CVXPY and call the solver, and parse the output. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. """ problem = convert_to_cvxpy(sdp) if solverparameters is not...
[ "Helper", "function", "to", "convert", "the", "SDP", "problem", "to", "CVXPY", "and", "call", "the", "solver", "and", "parse", "the", "output", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/cvxpy_utils.py#L14-L48
[ "def", "solve_with_cvxpy", "(", "sdp", ",", "solverparameters", "=", "None", ")", ":", "problem", "=", "convert_to_cvxpy", "(", "sdp", ")", "if", "solverparameters", "is", "not", "None", "and", "'solver'", "in", "solverparameters", ":", "solver", "=", "solverp...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
convert_to_cvxpy
Convert an SDP relaxation to a CVXPY problem. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`cvxpy.Problem`.
ncpol2sdpa/cvxpy_utils.py
def convert_to_cvxpy(sdp): """Convert an SDP relaxation to a CVXPY problem. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`cvxpy.Problem`. """ from cvxpy import Minimize, Problem, Variable row_offsets = [0] cumulative_sum = 0 for bl...
def convert_to_cvxpy(sdp): """Convert an SDP relaxation to a CVXPY problem. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`cvxpy.Problem`. """ from cvxpy import Minimize, Problem, Variable row_offsets = [0] cumulative_sum = 0 for bl...
[ "Convert", "an", "SDP", "relaxation", "to", "a", "CVXPY", "problem", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/cvxpy_utils.py#L51-L94
[ "def", "convert_to_cvxpy", "(", "sdp", ")", ":", "from", "cvxpy", "import", "Minimize", ",", "Problem", ",", "Variable", "row_offsets", "=", "[", "0", "]", "cumulative_sum", "=", "0", "for", "block_size", "in", "sdp", ".", "block_struct", ":", "cumulative_su...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
get_neighbors
Get the forward neighbors of a site in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Optional parameter to define width. :type width: int. :param periodic: O...
ncpol2sdpa/physics_utils.py
def get_neighbors(index, lattice_length, width=0, periodic=False): """Get the forward neighbors of a site in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Option...
def get_neighbors(index, lattice_length, width=0, periodic=False): """Get the forward neighbors of a site in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Option...
[ "Get", "the", "forward", "neighbors", "of", "a", "site", "in", "a", "lattice", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L17-L44
[ "def", "get_neighbors", "(", "index", ",", "lattice_length", ",", "width", "=", "0", ",", "periodic", "=", "False", ")", ":", "if", "width", "==", "0", ":", "width", "=", "lattice_length", "neighbors", "=", "[", "]", "coords", "=", "divmod", "(", "inde...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
get_next_neighbors
Get the forward neighbors at a given distance of a site or set of sites in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D lattice in either dimension :type lattice_length: int. :param width: Optional parameter to define width. ...
ncpol2sdpa/physics_utils.py
def get_next_neighbors(indices, lattice_length, width=0, distance=1, periodic=False): """Get the forward neighbors at a given distance of a site or set of sites in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D l...
def get_next_neighbors(indices, lattice_length, width=0, distance=1, periodic=False): """Get the forward neighbors at a given distance of a site or set of sites in a lattice. :param index: Linear index of operator. :type index: int. :param lattice_length: The size of the 2D l...
[ "Get", "the", "forward", "neighbors", "at", "a", "given", "distance", "of", "a", "site", "or", "set", "of", "sites", "in", "a", "lattice", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L47-L79
[ "def", "get_next_neighbors", "(", "indices", ",", "lattice_length", ",", "width", "=", "0", ",", "distance", "=", "1", ",", "periodic", "=", "False", ")", ":", "if", "not", "isinstance", "(", "indices", ",", "list", ")", ":", "indices", "=", "[", "indi...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
bosonic_constraints
Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions.
ncpol2sdpa/physics_utils.py
def bosonic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a): ...
def bosonic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a): ...
[ "Return", "a", "set", "of", "constraints", "that", "define", "fermionic", "ladder", "operators", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L82-L99
[ "def", "bosonic_constraints", "(", "a", ")", ":", "substitutions", "=", "{", "}", "for", "i", ",", "ai", "in", "enumerate", "(", "a", ")", ":", "substitutions", "[", "ai", "*", "Dagger", "(", "ai", ")", "]", "=", "1.0", "+", "Dagger", "(", "ai", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
fermionic_constraints
Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions.
ncpol2sdpa/physics_utils.py
def fermionic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a)...
def fermionic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a)...
[ "Return", "a", "set", "of", "constraints", "that", "define", "fermionic", "ladder", "operators", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L102-L121
[ "def", "fermionic_constraints", "(", "a", ")", ":", "substitutions", "=", "{", "}", "for", "i", ",", "ai", "in", "enumerate", "(", "a", ")", ":", "substitutions", "[", "ai", "**", "2", "]", "=", "0", "substitutions", "[", "Dagger", "(", "ai", ")", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
pauli_constraints
Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type Y: list of :class:`sympy.physics.quantum.operator.HermitianOperator`...
ncpol2sdpa/physics_utils.py
def pauli_constraints(X, Y, Z): """Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type Y: list of :class:`sympy.phys...
def pauli_constraints(X, Y, Z): """Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type Y: list of :class:`sympy.phys...
[ "Return", "a", "set", "of", "constraints", "that", "define", "Pauli", "spin", "operators", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L124-L163
[ "def", "pauli_constraints", "(", "X", ",", "Y", ",", "Z", ")", ":", "substitutions", "=", "{", "}", "n_vars", "=", "len", "(", "X", ")", "for", "i", "in", "range", "(", "n_vars", ")", ":", "# They square to the identity", "substitutions", "[", "X", "["...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
generate_measurements
Generate variables that behave like measurements. :param party: The list of number of measurement outputs a party has. :type party: list of int. :param label: The label to be given to the symbolic variables. :type label: str. :returns: list of list of :class:`sympy.physics.quantum.ope...
ncpol2sdpa/physics_utils.py
def generate_measurements(party, label): """Generate variables that behave like measurements. :param party: The list of number of measurement outputs a party has. :type party: list of int. :param label: The label to be given to the symbolic variables. :type label: str. :returns: list of list o...
def generate_measurements(party, label): """Generate variables that behave like measurements. :param party: The list of number of measurement outputs a party has. :type party: list of int. :param label: The label to be given to the symbolic variables. :type label: str. :returns: list of list o...
[ "Generate", "variables", "that", "behave", "like", "measurements", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L166-L181
[ "def", "generate_measurements", "(", "party", ",", "label", ")", ":", "measurements", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "party", ")", ")", ":", "measurements", ".", "append", "(", "generate_operators", "(", "label", "+", "'%s'", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
projective_measurement_constraints
Return a set of constraints that define projective measurements. :param parties: Measurements of different parties. :type A: list or tuple of list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: substitutions containing idempotency, orthogonality and ...
ncpol2sdpa/physics_utils.py
def projective_measurement_constraints(*parties): """Return a set of constraints that define projective measurements. :param parties: Measurements of different parties. :type A: list or tuple of list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: substitut...
def projective_measurement_constraints(*parties): """Return a set of constraints that define projective measurements. :param parties: Measurements of different parties. :type A: list or tuple of list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :returns: substitut...
[ "Return", "a", "set", "of", "constraints", "that", "define", "projective", "measurements", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L184-L216
[ "def", "projective_measurement_constraints", "(", "*", "parties", ")", ":", "substitutions", "=", "{", "}", "# Idempotency and orthogonality of projectors", "if", "isinstance", "(", "parties", "[", "0", "]", "[", "0", "]", "[", "0", "]", ",", "list", ")", ":",...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
define_objective_with_I
Define a polynomial using measurements and an I matrix describing a Bell inequality. :param I: The I matrix of a Bell inequality in the Collins-Gisin notation. :type I: list of list of int. :param args: Either the measurements of Alice and Bob or a `Probability` class describing their ...
ncpol2sdpa/physics_utils.py
def define_objective_with_I(I, *args): """Define a polynomial using measurements and an I matrix describing a Bell inequality. :param I: The I matrix of a Bell inequality in the Collins-Gisin notation. :type I: list of list of int. :param args: Either the measurements of Alice and Bob or a `Probabi...
def define_objective_with_I(I, *args): """Define a polynomial using measurements and an I matrix describing a Bell inequality. :param I: The I matrix of a Bell inequality in the Collins-Gisin notation. :type I: list of list of int. :param args: Either the measurements of Alice and Bob or a `Probabi...
[ "Define", "a", "polynomial", "using", "measurements", "and", "an", "I", "matrix", "describing", "a", "Bell", "inequality", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L219-L260
[ "def", "define_objective_with_I", "(", "I", ",", "*", "args", ")", ":", "objective", "=", "I", "[", "0", "]", "[", "0", "]", "if", "len", "(", "args", ")", ">", "2", "or", "len", "(", "args", ")", "==", "0", ":", "raise", "Exception", "(", "\"W...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
correlator
Correlators between the probabilities of two parties. :param A: Measurements of Alice. :type A: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param B: Measurements of Bob. :type B: list of list of :class:`sympy.physics.quantum.operator.HermitianOp...
ncpol2sdpa/physics_utils.py
def correlator(A, B): """Correlators between the probabilities of two parties. :param A: Measurements of Alice. :type A: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param B: Measurements of Bob. :type B: list of list of :class:`sympy.physics...
def correlator(A, B): """Correlators between the probabilities of two parties. :param A: Measurements of Alice. :type A: list of list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param B: Measurements of Bob. :type B: list of list of :class:`sympy.physics...
[ "Correlators", "between", "the", "probabilities", "of", "two", "parties", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L263-L288
[ "def", "correlator", "(", "A", ",", "B", ")", ":", "correlators", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "A", ")", ")", ":", "correlator_row", "=", "[", "]", "for", "j", "in", "range", "(", "len", "(", "B", ")", ")", ":", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
maximum_violation
Get the maximum violation of a two-party Bell inequality. :param A_configuration: Measurement settings of Alice. :type A_configuration: list of int. :param B_configuration: Measurement settings of Bob. :type B_configuration: list of int. :param I: The I matrix of a Bell inequality in the Collins-Gi...
ncpol2sdpa/physics_utils.py
def maximum_violation(A_configuration, B_configuration, I, level, extra=None): """Get the maximum violation of a two-party Bell inequality. :param A_configuration: Measurement settings of Alice. :type A_configuration: list of int. :param B_configuration: Measurement settings of Bob. :type B_configu...
def maximum_violation(A_configuration, B_configuration, I, level, extra=None): """Get the maximum violation of a two-party Bell inequality. :param A_configuration: Measurement settings of Alice. :type A_configuration: list of int. :param B_configuration: Measurement settings of Bob. :type B_configu...
[ "Get", "the", "maximum", "violation", "of", "a", "two", "-", "party", "Bell", "inequality", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L291-L316
[ "def", "maximum_violation", "(", "A_configuration", ",", "B_configuration", ",", "I", ",", "level", ",", "extra", "=", "None", ")", ":", "P", "=", "Probability", "(", "A_configuration", ",", "B_configuration", ")", "objective", "=", "define_objective_with_I", "(...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
stable_format_dict
A sorted, python2/3 stable formatting of a dictionary. Does not work for dicts with unicode strings as values.
curtsies/formatstring.py
def stable_format_dict(d): """A sorted, python2/3 stable formatting of a dictionary. Does not work for dicts with unicode strings as values.""" inner = ', '.join('{}: {}'.format(repr(k)[1:] if repr(k).startswith(u"u'") or repr(k).startswith(u'u"') ...
def stable_format_dict(d): """A sorted, python2/3 stable formatting of a dictionary. Does not work for dicts with unicode strings as values.""" inner = ', '.join('{}: {}'.format(repr(k)[1:] if repr(k).startswith(u"u'") or repr(k).startswith(u'u"') ...
[ "A", "sorted", "python2", "/", "3", "stable", "formatting", "of", "a", "dictionary", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L67-L76
[ "def", "stable_format_dict", "(", "d", ")", ":", "inner", "=", "', '", ".", "join", "(", "'{}: {}'", ".", "format", "(", "repr", "(", "k", ")", "[", "1", ":", "]", "if", "repr", "(", "k", ")", ".", "startswith", "(", "u\"u'\"", ")", "or", "repr",...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
interval_overlap
Returns by how much two intervals overlap assumed that a <= b and x <= y
curtsies/formatstring.py
def interval_overlap(a, b, x, y): """Returns by how much two intervals overlap assumed that a <= b and x <= y""" if b <= x or a >= y: return 0 elif x <= a <= y: return min(b, y) - a elif x <= b <= y: return b - max(a, x) elif a >= x and b <= y: return b - a e...
def interval_overlap(a, b, x, y): """Returns by how much two intervals overlap assumed that a <= b and x <= y""" if b <= x or a >= y: return 0 elif x <= a <= y: return min(b, y) - a elif x <= b <= y: return b - max(a, x) elif a >= x and b <= y: return b - a e...
[ "Returns", "by", "how", "much", "two", "intervals", "overlap" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L635-L648
[ "def", "interval_overlap", "(", "a", ",", "b", ",", "x", ",", "y", ")", ":", "if", "b", "<=", "x", "or", "a", ">=", "y", ":", "return", "0", "elif", "x", "<=", "a", "<=", "y", ":", "return", "min", "(", "b", ",", "y", ")", "-", "a", "elif...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
width_aware_slice
>>> width_aware_slice(u'a\uff25iou', 0, 2)[1] == u' ' True
curtsies/formatstring.py
def width_aware_slice(s, start, end, replacement_char=u' '): # type: (Text, int, int, Text) """ >>> width_aware_slice(u'a\uff25iou', 0, 2)[1] == u' ' True """ divides = [0] for c in s: divides.append(divides[-1] + wcswidth(c)) new_chunk_chars = [] for char, char_start, char_...
def width_aware_slice(s, start, end, replacement_char=u' '): # type: (Text, int, int, Text) """ >>> width_aware_slice(u'a\uff25iou', 0, 2)[1] == u' ' True """ divides = [0] for c in s: divides.append(divides[-1] + wcswidth(c)) new_chunk_chars = [] for char, char_start, char_...
[ ">>>", "width_aware_slice", "(", "u", "a", "\\", "uff25iou", "0", "2", ")", "[", "1", "]", "==", "u", "True" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L651-L671
[ "def", "width_aware_slice", "(", "s", ",", "start", ",", "end", ",", "replacement_char", "=", "u' '", ")", ":", "# type: (Text, int, int, Text)", "divides", "=", "[", "0", "]", "for", "c", "in", "s", ":", "divides", ".", "append", "(", "divides", "[", "-...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
linesplit
Returns a list of lines, split on the last possible space of each line. Split spaces will be removed. Whitespaces will be normalized to one space. Spaces will be the color of the first whitespace character of the normalized whitespace. If a word extends beyond the line, wrap it anyway. >>> linespl...
curtsies/formatstring.py
def linesplit(string, columns): # type: (Union[Text, FmtStr], int) -> List[FmtStr] """Returns a list of lines, split on the last possible space of each line. Split spaces will be removed. Whitespaces will be normalized to one space. Spaces will be the color of the first whitespace character of the ...
def linesplit(string, columns): # type: (Union[Text, FmtStr], int) -> List[FmtStr] """Returns a list of lines, split on the last possible space of each line. Split spaces will be removed. Whitespaces will be normalized to one space. Spaces will be the color of the first whitespace character of the ...
[ "Returns", "a", "list", "of", "lines", "split", "on", "the", "last", "possible", "space", "of", "each", "line", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L674-L705
[ "def", "linesplit", "(", "string", ",", "columns", ")", ":", "# type: (Union[Text, FmtStr], int) -> List[FmtStr]", "if", "not", "isinstance", "(", "string", ",", "FmtStr", ")", ":", "string", "=", "fmtstr", "(", "string", ")", "string_s", "=", "string", ".", "...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
normalize_slice
Fill in the Nones in a slice.
curtsies/formatstring.py
def normalize_slice(length, index): "Fill in the Nones in a slice." is_int = False if isinstance(index, int): is_int = True index = slice(index, index+1) if index.start is None: index = slice(0, index.stop, index.step) if index.stop is None: index = slice(index.start,...
def normalize_slice(length, index): "Fill in the Nones in a slice." is_int = False if isinstance(index, int): is_int = True index = slice(index, index+1) if index.start is None: index = slice(0, index.stop, index.step) if index.stop is None: index = slice(index.start,...
[ "Fill", "in", "the", "Nones", "in", "a", "slice", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L707-L726
[ "def", "normalize_slice", "(", "length", ",", "index", ")", ":", "is_int", "=", "False", "if", "isinstance", "(", "index", ",", "int", ")", ":", "is_int", "=", "True", "index", "=", "slice", "(", "index", ",", "index", "+", "1", ")", "if", "index", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
parse_args
Returns a kwargs dictionary by turning args into kwargs
curtsies/formatstring.py
def parse_args(args, kwargs): """Returns a kwargs dictionary by turning args into kwargs""" if 'style' in kwargs: args += (kwargs['style'],) del kwargs['style'] for arg in args: if not isinstance(arg, (bytes, unicode)): raise ValueError("args must be strings:" + repr(args...
def parse_args(args, kwargs): """Returns a kwargs dictionary by turning args into kwargs""" if 'style' in kwargs: args += (kwargs['style'],) del kwargs['style'] for arg in args: if not isinstance(arg, (bytes, unicode)): raise ValueError("args must be strings:" + repr(args...
[ "Returns", "a", "kwargs", "dictionary", "by", "turning", "args", "into", "kwargs" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L728-L759
[ "def", "parse_args", "(", "args", ",", "kwargs", ")", ":", "if", "'style'", "in", "kwargs", ":", "args", "+=", "(", "kwargs", "[", "'style'", "]", ",", ")", "del", "kwargs", "[", "'style'", "]", "for", "arg", "in", "args", ":", "if", "not", "isinst...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
fmtstr
Convenience function for creating a FmtStr >>> fmtstr('asdf', 'blue', 'on_red', 'bold') on_red(bold(blue('asdf'))) >>> fmtstr('blarg', fg='blue', bg='red', bold=True) on_red(bold(blue('blarg')))
curtsies/formatstring.py
def fmtstr(string, *args, **kwargs): # type: (Union[Text, bytes, FmtStr], *Any, **Any) -> FmtStr """ Convenience function for creating a FmtStr >>> fmtstr('asdf', 'blue', 'on_red', 'bold') on_red(bold(blue('asdf'))) >>> fmtstr('blarg', fg='blue', bg='red', bold=True) on_red(bold(blue('blarg...
def fmtstr(string, *args, **kwargs): # type: (Union[Text, bytes, FmtStr], *Any, **Any) -> FmtStr """ Convenience function for creating a FmtStr >>> fmtstr('asdf', 'blue', 'on_red', 'bold') on_red(bold(blue('asdf'))) >>> fmtstr('blarg', fg='blue', bg='red', bold=True) on_red(bold(blue('blarg...
[ "Convenience", "function", "for", "creating", "a", "FmtStr" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L761-L778
[ "def", "fmtstr", "(", "string", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (Union[Text, bytes, FmtStr], *Any, **Any) -> FmtStr", "atts", "=", "parse_args", "(", "args", ",", "kwargs", ")", "if", "isinstance", "(", "string", ",", "FmtStr", ")...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
Chunk.color_str
Return an escape-coded string to write to the terminal.
curtsies/formatstring.py
def color_str(self): "Return an escape-coded string to write to the terminal." s = self.s for k, v in sorted(self.atts.items()): # (self.atts sorted for the sake of always acting the same.) if k not in xforms: # Unsupported SGR code continu...
def color_str(self): "Return an escape-coded string to write to the terminal." s = self.s for k, v in sorted(self.atts.items()): # (self.atts sorted for the sake of always acting the same.) if k not in xforms: # Unsupported SGR code continu...
[ "Return", "an", "escape", "-", "coded", "string", "to", "write", "to", "the", "terminal", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L106-L120
[ "def", "color_str", "(", "self", ")", ":", "s", "=", "self", ".", "s", "for", "k", ",", "v", "in", "sorted", "(", "self", ".", "atts", ".", "items", "(", ")", ")", ":", "# (self.atts sorted for the sake of always acting the same.)", "if", "k", "not", "in...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
Chunk.repr_part
FmtStr repr is build by concatenating these.
curtsies/formatstring.py
def repr_part(self): """FmtStr repr is build by concatenating these.""" def pp_att(att): if att == 'fg': return FG_NUMBER_TO_COLOR[self.atts[att]] elif att == 'bg': return 'on_' + BG_NUMBER_TO_COLOR[self.atts[att]] else: return att atts_out = dict((k, v) for (...
def repr_part(self): """FmtStr repr is build by concatenating these.""" def pp_att(att): if att == 'fg': return FG_NUMBER_TO_COLOR[self.atts[att]] elif att == 'bg': return 'on_' + BG_NUMBER_TO_COLOR[self.atts[att]] else: return att atts_out = dict((k, v) for (...
[ "FmtStr", "repr", "is", "build", "by", "concatenating", "these", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L144-L152
[ "def", "repr_part", "(", "self", ")", ":", "def", "pp_att", "(", "att", ")", ":", "if", "att", "==", "'fg'", ":", "return", "FG_NUMBER_TO_COLOR", "[", "self", ".", "atts", "[", "att", "]", "]", "elif", "att", "==", "'bg'", ":", "return", "'on_'", "...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
ChunkSplitter.request
Requests a sub-chunk of max_width or shorter. Returns None if no chunks left.
curtsies/formatstring.py
def request(self, max_width): # type: (int) -> Optional[Tuple[int, Chunk]] """Requests a sub-chunk of max_width or shorter. Returns None if no chunks left.""" if max_width < 1: raise ValueError('requires positive integer max_width') s = self.chunk.s length = len(s) ...
def request(self, max_width): # type: (int) -> Optional[Tuple[int, Chunk]] """Requests a sub-chunk of max_width or shorter. Returns None if no chunks left.""" if max_width < 1: raise ValueError('requires positive integer max_width') s = self.chunk.s length = len(s) ...
[ "Requests", "a", "sub", "-", "chunk", "of", "max_width", "or", "shorter", ".", "Returns", "None", "if", "no", "chunks", "left", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L180-L220
[ "def", "request", "(", "self", ",", "max_width", ")", ":", "# type: (int) -> Optional[Tuple[int, Chunk]]", "if", "max_width", "<", "1", ":", "raise", "ValueError", "(", "'requires positive integer max_width'", ")", "s", "=", "self", ".", "chunk", ".", "s", "length...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.from_str
r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue')+"|") '|'+on_blue(red('hey'))+'|' >>> fmtstr('|\x1b[31m\x1b...
curtsies/formatstring.py
def from_str(cls, s): # type: (Union[Text, bytes]) -> FmtStr r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue...
def from_str(cls, s): # type: (Union[Text, bytes]) -> FmtStr r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue...
[ "r", "Return", "a", "FmtStr", "representing", "input", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L239-L273
[ "def", "from_str", "(", "cls", ",", "s", ")", ":", "# type: (Union[Text, bytes]) -> FmtStr", "if", "'\\x1b['", "in", "s", ":", "try", ":", "tokens_and_strings", "=", "parse", "(", "s", ")", "except", "ValueError", ":", "return", "FmtStr", "(", "Chunk", "(", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.copy_with_new_str
Copies the current FmtStr's attributes while changing its string.
curtsies/formatstring.py
def copy_with_new_str(self, new_str): """Copies the current FmtStr's attributes while changing its string.""" # What to do when there are multiple Chunks with conflicting atts? old_atts = dict((att, value) for bfs in self.chunks for (att, value) in bfs.atts.items()) r...
def copy_with_new_str(self, new_str): """Copies the current FmtStr's attributes while changing its string.""" # What to do when there are multiple Chunks with conflicting atts? old_atts = dict((att, value) for bfs in self.chunks for (att, value) in bfs.atts.items()) r...
[ "Copies", "the", "current", "FmtStr", "s", "attributes", "while", "changing", "its", "string", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L275-L280
[ "def", "copy_with_new_str", "(", "self", ",", "new_str", ")", ":", "# What to do when there are multiple Chunks with conflicting atts?", "old_atts", "=", "dict", "(", "(", "att", ",", "value", ")", "for", "bfs", "in", "self", ".", "chunks", "for", "(", "att", ",...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.setitem
Shim for easily converting old __setitem__ calls
curtsies/formatstring.py
def setitem(self, startindex, fs): """Shim for easily converting old __setitem__ calls""" return self.setslice_with_length(startindex, startindex+1, fs, len(self))
def setitem(self, startindex, fs): """Shim for easily converting old __setitem__ calls""" return self.setslice_with_length(startindex, startindex+1, fs, len(self))
[ "Shim", "for", "easily", "converting", "old", "__setitem__", "calls" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L282-L284
[ "def", "setitem", "(", "self", ",", "startindex", ",", "fs", ")", ":", "return", "self", ".", "setslice_with_length", "(", "startindex", ",", "startindex", "+", "1", ",", "fs", ",", "len", "(", "self", ")", ")" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.setslice_with_length
Shim for easily converting old __setitem__ calls
curtsies/formatstring.py
def setslice_with_length(self, startindex, endindex, fs, length): """Shim for easily converting old __setitem__ calls""" if len(self) < startindex: fs = ' '*(startindex - len(self)) + fs if len(self) > endindex: fs = fs + ' '*(endindex - startindex - len(fs)) ...
def setslice_with_length(self, startindex, endindex, fs, length): """Shim for easily converting old __setitem__ calls""" if len(self) < startindex: fs = ' '*(startindex - len(self)) + fs if len(self) > endindex: fs = fs + ' '*(endindex - startindex - len(fs)) ...
[ "Shim", "for", "easily", "converting", "old", "__setitem__", "calls" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L286-L295
[ "def", "setslice_with_length", "(", "self", ",", "startindex", ",", "endindex", ",", "fs", ",", "length", ")", ":", "if", "len", "(", "self", ")", "<", "startindex", ":", "fs", "=", "' '", "*", "(", "startindex", "-", "len", "(", "self", ")", ")", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.splice
Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided, new_str will replace the substring self.s[start:end-1].
curtsies/formatstring.py
def splice(self, new_str, start, end=None): """Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided, new_str will replace the substring self.s[start:end-1]. """ if len(new_str) == 0: return self n...
def splice(self, new_str, start, end=None): """Returns a new FmtStr with the input string spliced into the the original FmtStr at start and end. If end is provided, new_str will replace the substring self.s[start:end-1]. """ if len(new_str) == 0: return self n...
[ "Returns", "a", "new", "FmtStr", "with", "the", "input", "string", "spliced", "into", "the", "the", "original", "FmtStr", "at", "start", "and", "end", ".", "If", "end", "is", "provided", "new_str", "will", "replace", "the", "substring", "self", ".", "s", ...
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L297-L343
[ "def", "splice", "(", "self", ",", "new_str", ",", "start", ",", "end", "=", "None", ")", ":", "if", "len", "(", "new_str", ")", "==", "0", ":", "return", "self", "new_fs", "=", "new_str", "if", "isinstance", "(", "new_str", ",", "FmtStr", ")", "el...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.copy_with_new_atts
Returns a new FmtStr with the same content but new formatting
curtsies/formatstring.py
def copy_with_new_atts(self, **attributes): """Returns a new FmtStr with the same content but new formatting""" return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes)) for bfs in self.chunks])
def copy_with_new_atts(self, **attributes): """Returns a new FmtStr with the same content but new formatting""" return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes)) for bfs in self.chunks])
[ "Returns", "a", "new", "FmtStr", "with", "the", "same", "content", "but", "new", "formatting" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L348-L351
[ "def", "copy_with_new_atts", "(", "self", ",", "*", "*", "attributes", ")", ":", "return", "FmtStr", "(", "*", "[", "Chunk", "(", "bfs", ".", "s", ",", "bfs", ".", "atts", ".", "extend", "(", "attributes", ")", ")", "for", "bfs", "in", "self", ".",...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.join
Joins an iterable yielding strings or FmtStrs with self as separator
curtsies/formatstring.py
def join(self, iterable): """Joins an iterable yielding strings or FmtStrs with self as separator""" before = [] chunks = [] for i, s in enumerate(iterable): chunks.extend(before) before = self.chunks if isinstance(s, FmtStr): chunks.ex...
def join(self, iterable): """Joins an iterable yielding strings or FmtStrs with self as separator""" before = [] chunks = [] for i, s in enumerate(iterable): chunks.extend(before) before = self.chunks if isinstance(s, FmtStr): chunks.ex...
[ "Joins", "an", "iterable", "yielding", "strings", "or", "FmtStrs", "with", "self", "as", "separator" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L353-L366
[ "def", "join", "(", "self", ",", "iterable", ")", ":", "before", "=", "[", "]", "chunks", "=", "[", "]", "for", "i", ",", "s", "in", "enumerate", "(", "iterable", ")", ":", "chunks", ".", "extend", "(", "before", ")", "before", "=", "self", ".", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.split
Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.
curtsies/formatstring.py
def split(self, sep=None, maxsplit=None, regex=False): """Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.""" if maxsplit is not None: raise NotImplementedError('no max...
def split(self, sep=None, maxsplit=None, regex=False): """Split based on seperator, optionally using a regex Capture groups are ignored in regex, the whole pattern is matched and used to split the original FmtStr.""" if maxsplit is not None: raise NotImplementedError('no max...
[ "Split", "based", "on", "seperator", "optionally", "using", "a", "regex" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L369-L384
[ "def", "split", "(", "self", ",", "sep", "=", "None", ",", "maxsplit", "=", "None", ",", "regex", "=", "False", ")", ":", "if", "maxsplit", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "'no maxsplit yet'", ")", "s", "=", "self", ".", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.splitlines
Return a list of lines, split on newline characters, include line boundaries, if keepends is true.
curtsies/formatstring.py
def splitlines(self, keepends=False): """Return a list of lines, split on newline characters, include line boundaries, if keepends is true.""" lines = self.split('\n') return [line+'\n' for line in lines] if keepends else ( lines if lines[-1] else lines[:-1])
def splitlines(self, keepends=False): """Return a list of lines, split on newline characters, include line boundaries, if keepends is true.""" lines = self.split('\n') return [line+'\n' for line in lines] if keepends else ( lines if lines[-1] else lines[:-1])
[ "Return", "a", "list", "of", "lines", "split", "on", "newline", "characters", "include", "line", "boundaries", "if", "keepends", "is", "true", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L386-L391
[ "def", "splitlines", "(", "self", ",", "keepends", "=", "False", ")", ":", "lines", "=", "self", ".", "split", "(", "'\\n'", ")", "return", "[", "line", "+", "'\\n'", "for", "line", "in", "lines", "]", "if", "keepends", "else", "(", "lines", "if", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.ljust
S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved
curtsies/formatstring.py
def ljust(self, width, fillchar=None): """S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved """ if fillchar is not None: return fmtstr(self.s.ljust(width, fillchar), **self.shared_atts) to_add = ' ' * (width...
def ljust(self, width, fillchar=None): """S.ljust(width[, fillchar]) -> string If a fillchar is provided, less formatting information will be preserved """ if fillchar is not None: return fmtstr(self.s.ljust(width, fillchar), **self.shared_atts) to_add = ' ' * (width...
[ "S", ".", "ljust", "(", "width", "[", "fillchar", "]", ")", "-", ">", "string" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L395-L408
[ "def", "ljust", "(", "self", ",", "width", ",", "fillchar", "=", "None", ")", ":", "if", "fillchar", "is", "not", "None", ":", "return", "fmtstr", "(", "self", ".", "s", ".", "ljust", "(", "width", ",", "fillchar", ")", ",", "*", "*", "self", "."...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.width
The number of columns it would take to display this string
curtsies/formatstring.py
def width(self): """The number of columns it would take to display this string""" if self._width is not None: return self._width self._width = sum(fs.width for fs in self.chunks) return self._width
def width(self): """The number of columns it would take to display this string""" if self._width is not None: return self._width self._width = sum(fs.width for fs in self.chunks) return self._width
[ "The", "number", "of", "columns", "it", "would", "take", "to", "display", "this", "string" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L447-L452
[ "def", "width", "(", "self", ")", ":", "if", "self", ".", "_width", "is", "not", "None", ":", "return", "self", ".", "_width", "self", ".", "_width", "=", "sum", "(", "fs", ".", "width", "for", "fs", "in", "self", ".", "chunks", ")", "return", "s...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.width_at_offset
Returns the horizontal position of character n of the string
curtsies/formatstring.py
def width_at_offset(self, n): """Returns the horizontal position of character n of the string""" #TODO make more efficient? width = wcswidth(self.s[:n]) assert width != -1 return width
def width_at_offset(self, n): """Returns the horizontal position of character n of the string""" #TODO make more efficient? width = wcswidth(self.s[:n]) assert width != -1 return width
[ "Returns", "the", "horizontal", "position", "of", "character", "n", "of", "the", "string" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L454-L459
[ "def", "width_at_offset", "(", "self", ",", "n", ")", ":", "#TODO make more efficient?", "width", "=", "wcswidth", "(", "self", ".", "s", "[", ":", "n", "]", ")", "assert", "width", "!=", "-", "1", "return", "width" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.shared_atts
Gets atts shared among all nonzero length component Chunk
curtsies/formatstring.py
def shared_atts(self): """Gets atts shared among all nonzero length component Chunk""" #TODO cache this, could get ugly for large FmtStrs atts = {} first = self.chunks[0] for att in sorted(first.atts): #TODO how to write this without the '???'? if all(fs.a...
def shared_atts(self): """Gets atts shared among all nonzero length component Chunk""" #TODO cache this, could get ugly for large FmtStrs atts = {} first = self.chunks[0] for att in sorted(first.atts): #TODO how to write this without the '???'? if all(fs.a...
[ "Gets", "atts", "shared", "among", "all", "nonzero", "length", "component", "Chunk" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L494-L503
[ "def", "shared_atts", "(", "self", ")", ":", "#TODO cache this, could get ugly for large FmtStrs", "atts", "=", "{", "}", "first", "=", "self", ".", "chunks", "[", "0", "]", "for", "att", "in", "sorted", "(", "first", ".", "atts", ")", ":", "#TODO how to wri...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.new_with_atts_removed
Returns a new FmtStr with the same content but some attributes removed
curtsies/formatstring.py
def new_with_atts_removed(self, *attributes): """Returns a new FmtStr with the same content but some attributes removed""" return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes)) for bfs in self.chunks])
def new_with_atts_removed(self, *attributes): """Returns a new FmtStr with the same content but some attributes removed""" return FmtStr(*[Chunk(bfs.s, bfs.atts.remove(*attributes)) for bfs in self.chunks])
[ "Returns", "a", "new", "FmtStr", "with", "the", "same", "content", "but", "some", "attributes", "removed" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L505-L508
[ "def", "new_with_atts_removed", "(", "self", ",", "*", "attributes", ")", ":", "return", "FmtStr", "(", "*", "[", "Chunk", "(", "bfs", ".", "s", ",", "bfs", ".", "atts", ".", "remove", "(", "*", "attributes", ")", ")", "for", "bfs", "in", "self", "...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.divides
List of indices of divisions between the constituent chunks.
curtsies/formatstring.py
def divides(self): """List of indices of divisions between the constituent chunks.""" acc = [0] for s in self.chunks: acc.append(acc[-1] + len(s)) return acc
def divides(self): """List of indices of divisions between the constituent chunks.""" acc = [0] for s in self.chunks: acc.append(acc[-1] + len(s)) return acc
[ "List", "of", "indices", "of", "divisions", "between", "the", "constituent", "chunks", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L525-L530
[ "def", "divides", "(", "self", ")", ":", "acc", "=", "[", "0", "]", "for", "s", "in", "self", ".", "chunks", ":", "acc", ".", "append", "(", "acc", "[", "-", "1", "]", "+", "len", "(", "s", ")", ")", "return", "acc" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.width_aware_slice
Slice based on the number of columns it would take to display the substring.
curtsies/formatstring.py
def width_aware_slice(self, index): """Slice based on the number of columns it would take to display the substring.""" if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') index = normalize_slice(self.width, index) counter = 0 parts = [] ...
def width_aware_slice(self, index): """Slice based on the number of columns it would take to display the substring.""" if wcswidth(self.s) == -1: raise ValueError('bad values for width aware slicing') index = normalize_slice(self.width, index) counter = 0 parts = [] ...
[ "Slice", "based", "on", "the", "number", "of", "columns", "it", "would", "take", "to", "display", "the", "substring", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L557-L576
[ "def", "width_aware_slice", "(", "self", ",", "index", ")", ":", "if", "wcswidth", "(", "self", ".", "s", ")", "==", "-", "1", ":", "raise", "ValueError", "(", "'bad values for width aware slicing'", ")", "index", "=", "normalize_slice", "(", "self", ".", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr.width_aware_splitlines
Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line.
curtsies/formatstring.py
def width_aware_splitlines(self, columns): # type: (int) -> Iterator[FmtStr] """Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line. """ if columns ...
def width_aware_splitlines(self, columns): # type: (int) -> Iterator[FmtStr] """Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line. """ if columns ...
[ "Split", "into", "lines", "pushing", "doublewidth", "characters", "at", "the", "end", "of", "a", "line", "to", "the", "next", "line", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L578-L588
[ "def", "width_aware_splitlines", "(", "self", ",", "columns", ")", ":", "# type: (int) -> Iterator[FmtStr]", "if", "columns", "<", "2", ":", "raise", "ValueError", "(", "\"Column width %s is too narrow.\"", "%", "columns", ")", "if", "wcswidth", "(", "self", ".", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FmtStr._getitem_normalized
Builds the more compact fmtstrs by using fromstr( of the control sequences)
curtsies/formatstring.py
def _getitem_normalized(self, index): """Builds the more compact fmtstrs by using fromstr( of the control sequences)""" index = normalize_slice(len(self), index) counter = 0 output = '' for fs in self.chunks: if index.start < counter + len(fs) and index.stop > counter...
def _getitem_normalized(self, index): """Builds the more compact fmtstrs by using fromstr( of the control sequences)""" index = normalize_slice(len(self), index) counter = 0 output = '' for fs in self.chunks: if index.start < counter + len(fs) and index.stop > counter...
[ "Builds", "the", "more", "compact", "fmtstrs", "by", "using", "fromstr", "(", "of", "the", "control", "sequences", ")" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L613-L626
[ "def", "_getitem_normalized", "(", "self", ",", "index", ")", ":", "index", "=", "normalize_slice", "(", "len", "(", "self", ")", ",", "index", ")", "counter", "=", "0", "output", "=", "''", "for", "fs", "in", "self", ".", "chunks", ":", "if", "index...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
MoroderHierarchy._calculate_block_structure
Calculates the block_struct array for the output file.
ncpol2sdpa/moroder_hierarchy.py
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the outp...
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the outp...
[ "Calculates", "the", "block_struct", "array", "for", "the", "output", "file", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/moroder_hierarchy.py#L81-L101
[ "def", "_calculate_block_structure", "(", "self", ",", "inequalities", ",", "equalities", ",", "momentinequalities", ",", "momentequalities", ",", "extramomentmatrix", ",", "removeequalities", ",", "block_struct", "=", "None", ")", ":", "block_struct", "=", "[", "]"...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
main
Ideally we shouldn't lose the first second of events
examples/initial_input.py
def main(): """Ideally we shouldn't lose the first second of events""" time.sleep(1) with Input() as input_generator: for e in input_generator: print(repr(e))
def main(): """Ideally we shouldn't lose the first second of events""" time.sleep(1) with Input() as input_generator: for e in input_generator: print(repr(e))
[ "Ideally", "we", "shouldn", "t", "lose", "the", "first", "second", "of", "events" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/initial_input.py#L5-L10
[ "def", "main", "(", ")", ":", "time", ".", "sleep", "(", "1", ")", "with", "Input", "(", ")", "as", "input_generator", ":", "for", "e", "in", "input_generator", ":", "print", "(", "repr", "(", "e", ")", ")" ]
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
SteeringHierarchy._process_monomial
Process a single monomial when building the moment matrix.
ncpol2sdpa/steering_hierarchy.py
def _process_monomial(self, monomial, n_vars): """Process a single monomial when building the moment matrix. """ coeff, monomial = monomial.as_coeff_Mul() k = 0 # Have we seen this monomial before? conjugate = False try: # If yes, then we improve spars...
def _process_monomial(self, monomial, n_vars): """Process a single monomial when building the moment matrix. """ coeff, monomial = monomial.as_coeff_Mul() k = 0 # Have we seen this monomial before? conjugate = False try: # If yes, then we improve spars...
[ "Process", "a", "single", "monomial", "when", "building", "the", "moment", "matrix", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L80-L108
[ "def", "_process_monomial", "(", "self", ",", "monomial", ",", "n_vars", ")", ":", "coeff", ",", "monomial", "=", "monomial", ".", "as_coeff_Mul", "(", ")", "k", "=", "0", "# Have we seen this monomial before?", "conjugate", "=", "False", "try", ":", "# If yes...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
SteeringHierarchy.__get_trace_facvar
Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse, but instead of pushing sparse entries to the constraint matrices, it returns a dense vector.
ncpol2sdpa/steering_hierarchy.py
def __get_trace_facvar(self, polynomial): """Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse, but instead of pushing sparse entries to the constraint matrices, it returns a dense vector. """ facvar = [0] * (sel...
def __get_trace_facvar(self, polynomial): """Return dense vector representation of a polynomial. This function is nearly identical to __push_facvar_sparse, but instead of pushing sparse entries to the constraint matrices, it returns a dense vector. """ facvar = [0] * (sel...
[ "Return", "dense", "vector", "representation", "of", "a", "polynomial", ".", "This", "function", "is", "nearly", "identical", "to", "__push_facvar_sparse", "but", "instead", "of", "pushing", "sparse", "entries", "to", "the", "constraint", "matrices", "it", "return...
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L186-L219
[ "def", "__get_trace_facvar", "(", "self", ",", "polynomial", ")", ":", "facvar", "=", "[", "0", "]", "*", "(", "self", ".", "n_vars", "+", "1", ")", "F", "=", "{", "}", "for", "i", "in", "range", "(", "self", ".", "matrix_var_dim", ")", ":", "for...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
SteeringHierarchy.set_objective
Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a string expression of a linear combina...
ncpol2sdpa/steering_hierarchy.py
def set_objective(self, objective, extraobjexpr=None): """Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a ...
def set_objective(self, objective, extraobjexpr=None): """Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a ...
[ "Set", "or", "change", "the", "objective", "function", "of", "the", "polynomial", "optimization", "problem", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L221-L242
[ "def", "set_objective", "(", "self", ",", "objective", ",", "extraobjexpr", "=", "None", ")", ":", "if", "objective", "is", "not", "None", "and", "self", ".", "matrix_var_dim", "is", "not", "None", ":", "facvar", "=", "self", ".", "__get_trace_facvar", "("...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
SteeringHierarchy._calculate_block_structure
Calculates the block_struct array for the output file.
ncpol2sdpa/steering_hierarchy.py
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the outp...
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the outp...
[ "Calculates", "the", "block_struct", "array", "for", "the", "output", "file", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L244-L256
[ "def", "_calculate_block_structure", "(", "self", ",", "inequalities", ",", "equalities", ",", "momentinequalities", ",", "momentequalities", ",", "extramomentmatrix", ",", "removeequalities", ",", "block_struct", "=", "None", ")", ":", "super", "(", "SteeringHierarch...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
SteeringHierarchy.write_to_file
Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or .txt for a symbolic export ...
ncpol2sdpa/steering_hierarchy.py
def write_to_file(self, filename, filetype=None): """Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or...
def write_to_file(self, filename, filetype=None): """Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or...
[ "Write", "the", "relaxation", "to", "a", "file", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L268-L315
[ "def", "write_to_file", "(", "self", ",", "filename", ",", "filetype", "=", "None", ")", ":", "if", "filetype", "==", "\"txt\"", "and", "not", "filename", ".", "endswith", "(", "\".txt\"", ")", ":", "raise", "Exception", "(", "\"TXT files must have .txt extens...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
BaseFinder.get_outerframe_skip_importlib_frame
There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bug is fixed
ezcf/_base.py
def get_outerframe_skip_importlib_frame(level): """ There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bug is fixed """ if sys.version_info < (3, 4): return sys._getframe(level) else: curre...
def get_outerframe_skip_importlib_frame(level): """ There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bug is fixed """ if sys.version_info < (3, 4): return sys._getframe(level) else: curre...
[ "There", "s", "a", "bug", "in", "Python3", ".", "4", "+", "see", "http", ":", "//", "bugs", ".", "python", ".", "org", "/", "issue23773", "remove", "this", "and", "use", "sys", ".", "_getframe", "(", "3", ")", "when", "bug", "is", "fixed" ]
laike9m/ezcf
python
https://github.com/laike9m/ezcf/blob/30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12/ezcf/_base.py#L46-L62
[ "def", "get_outerframe_skip_importlib_frame", "(", "level", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "4", ")", ":", "return", "sys", ".", "_getframe", "(", "level", ")", "else", ":", "currentframe", "=", "inspect", ".", "currentframe...
30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12
train
Market.public_api
template function of public api
coincheck/market.py
def public_api(self,url): ''' template function of public api''' try : url in api_urls return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text) except Exception as e: print(e)
def public_api(self,url): ''' template function of public api''' try : url in api_urls return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text) except Exception as e: print(e)
[ "template", "function", "of", "public", "api" ]
kmn/coincheck
python
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/market.py#L19-L25
[ "def", "public_api", "(", "self", ",", "url", ")", ":", "try", ":", "url", "in", "api_urls", "return", "ast", ".", "literal_eval", "(", "requests", ".", "get", "(", "base_url", "+", "api_urls", ".", "get", "(", "url", ")", ")", ".", "text", ")", "e...
4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc
train
parse
r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m")
curtsies/escseqparse.py
def parse(s): r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\...
def parse(s): r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\...
[ "r", "Returns", "a", "list", "of", "strings", "or", "format", "dictionaries", "to", "describe", "the", "strings", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/escseqparse.py#L23-L48
[ "def", "parse", "(", "s", ")", ":", "stuff", "=", "[", "]", "rest", "=", "s", "while", "True", ":", "front", ",", "token", ",", "rest", "=", "peel_off_esc_code", "(", "rest", ")", "if", "front", ":", "stuff", ".", "append", "(", "front", ")", "if...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
peel_off_esc_code
r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True
curtsies/escseqparse.py
def peel_off_esc_code(s): r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True ...
def peel_off_esc_code(s): r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True ...
[ "r", "Returns", "processed", "text", "the", "next", "token", "and", "unprocessed", "text" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/escseqparse.py#L51-L92
[ "def", "peel_off_esc_code", "(", "s", ")", ":", "p", "=", "r\"\"\"(?P<front>.*?)\n (?P<seq>\n (?P<csi>\n (?:[\u001b]\\[)\n |\n [\"\"\"", "+", "'\\x9b'", "+", "r\"\"\"])\n (?P<private>)\n ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
get_key
Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should match the terminal encoding. keynames is a string describing how key...
curtsies/events.py
def get_key(bytes_, encoding, keynames='curtsies', full=False): """Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should ma...
def get_key(bytes_, encoding, keynames='curtsies', full=False): """Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should ma...
[ "Return", "key", "pressed", "from", "bytes_", "or", "None" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/events.py#L142-L218
[ "def", "get_key", "(", "bytes_", ",", "encoding", ",", "keynames", "=", "'curtsies'", ",", "full", "=", "False", ")", ":", "if", "not", "all", "(", "isinstance", "(", "c", ",", "type", "(", "b''", ")", ")", "for", "c", "in", "bytes_", ")", ":", "...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
could_be_unfinished_char
Whether seq bytes might create a char in encoding if more bytes were added
curtsies/events.py
def could_be_unfinished_char(seq, encoding): """Whether seq bytes might create a char in encoding if more bytes were added""" if decodable(seq, encoding): return False # any sensible encoding surely doesn't require lookahead (right?) # (if seq bytes encoding a character, adding another byte shou...
def could_be_unfinished_char(seq, encoding): """Whether seq bytes might create a char in encoding if more bytes were added""" if decodable(seq, encoding): return False # any sensible encoding surely doesn't require lookahead (right?) # (if seq bytes encoding a character, adding another byte shou...
[ "Whether", "seq", "bytes", "might", "create", "a", "char", "in", "encoding", "if", "more", "bytes", "were", "added" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/events.py#L220-L231
[ "def", "could_be_unfinished_char", "(", "seq", ",", "encoding", ")", ":", "if", "decodable", "(", "seq", ",", "encoding", ")", ":", "return", "False", "# any sensible encoding surely doesn't require lookahead (right?)", "# (if seq bytes encoding a character, adding another byte...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
pp_event
Returns pretty representation of an Event or keypress
curtsies/events.py
def pp_event(seq): """Returns pretty representation of an Event or keypress""" if isinstance(seq, Event): return str(seq) # Get the original sequence back if seq is a pretty name already rev_curses = dict((v, k) for k, v in CURSES_NAMES.items()) rev_curtsies = dict((v, k) for k, v in CURTS...
def pp_event(seq): """Returns pretty representation of an Event or keypress""" if isinstance(seq, Event): return str(seq) # Get the original sequence back if seq is a pretty name already rev_curses = dict((v, k) for k, v in CURSES_NAMES.items()) rev_curtsies = dict((v, k) for k, v in CURTS...
[ "Returns", "pretty", "representation", "of", "an", "Event", "or", "keypress" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/events.py#L243-L260
[ "def", "pp_event", "(", "seq", ")", ":", "if", "isinstance", "(", "seq", ",", "Event", ")", ":", "return", "str", "(", "seq", ")", "# Get the original sequence back if seq is a pretty name already", "rev_curses", "=", "dict", "(", "(", "v", ",", "k", ")", "f...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
create_nouns
Return a string of random nouns up to max number
barnum/gen_data.py
def create_nouns(max=2): """ Return a string of random nouns up to max number """ nouns = [] for noun in range(0, max): nouns.append(random.choice(noun_list)) return " ".join(nouns)
def create_nouns(max=2): """ Return a string of random nouns up to max number """ nouns = [] for noun in range(0, max): nouns.append(random.choice(noun_list)) return " ".join(nouns)
[ "Return", "a", "string", "of", "random", "nouns", "up", "to", "max", "number" ]
chris1610/barnum-proj
python
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L112-L119
[ "def", "create_nouns", "(", "max", "=", "2", ")", ":", "nouns", "=", "[", "]", "for", "noun", "in", "range", "(", "0", ",", "max", ")", ":", "nouns", ".", "append", "(", "random", ".", "choice", "(", "noun_list", ")", ")", "return", "\" \"", ".",...
0a38f24bde66373553d02fbf67b733c1d55ada33
train
create_date
Create a random valid date If past, then dates can be in the past If into the future, then no more than max_years into the future If it's not, then it can't be any older than max_years_past
barnum/gen_data.py
def create_date(past=False, max_years_future=10, max_years_past=10): """ Create a random valid date If past, then dates can be in the past If into the future, then no more than max_years into the future If it's not, then it can't be any older than max_years_past """ if past: start = ...
def create_date(past=False, max_years_future=10, max_years_past=10): """ Create a random valid date If past, then dates can be in the past If into the future, then no more than max_years into the future If it's not, then it can't be any older than max_years_past """ if past: start = ...
[ "Create", "a", "random", "valid", "date", "If", "past", "then", "dates", "can", "be", "in", "the", "past", "If", "into", "the", "future", "then", "no", "more", "than", "max_years", "into", "the", "future", "If", "it", "s", "not", "then", "it", "can", ...
chris1610/barnum-proj
python
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L122-L139
[ "def", "create_date", "(", "past", "=", "False", ",", "max_years_future", "=", "10", ",", "max_years_past", "=", "10", ")", ":", "if", "past", ":", "start", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "-", "datetime", ".", "timedelta", "(...
0a38f24bde66373553d02fbf67b733c1d55ada33
train
create_birthday
Create a random birthday fomr someone between the ages of min_age and max_age
barnum/gen_data.py
def create_birthday(min_age=18, max_age=80): """ Create a random birthday fomr someone between the ages of min_age and max_age """ age = random.randint(min_age, max_age) start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365)) return start - datetime.timedelta(days=age * 3...
def create_birthday(min_age=18, max_age=80): """ Create a random birthday fomr someone between the ages of min_age and max_age """ age = random.randint(min_age, max_age) start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365)) return start - datetime.timedelta(days=age * 3...
[ "Create", "a", "random", "birthday", "fomr", "someone", "between", "the", "ages", "of", "min_age", "and", "max_age" ]
chris1610/barnum-proj
python
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L142-L148
[ "def", "create_birthday", "(", "min_age", "=", "18", ",", "max_age", "=", "80", ")", ":", "age", "=", "random", ".", "randint", "(", "min_age", ",", "max_age", ")", "start", "=", "datetime", ".", "date", ".", "today", "(", ")", "-", "datetime", ".", ...
0a38f24bde66373553d02fbf67b733c1d55ada33
train
create_pw
Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :param length: Maximum no. of characters in the password :typ...
barnum/gen_data.py
def create_pw(length=8, digits=2, upper=2, lower=2): """Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :para...
def create_pw(length=8, digits=2, upper=2, lower=2): """Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :para...
[ "Create", "a", "random", "password", "From", "Stackoverflow", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "7479442", "/", "high", "-", "quality", "-", "simple", "-", "random", "-", "password", "-", "generator" ]
chris1610/barnum-proj
python
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L189-L227
[ "def", "create_pw", "(", "length", "=", "8", ",", "digits", "=", "2", ",", "upper", "=", "2", ",", "lower", "=", "2", ")", ":", "seed", "(", "time", "(", ")", ")", "lowercase", "=", "string", ".", "ascii_lowercase", "uppercase", "=", "string", ".",...
0a38f24bde66373553d02fbf67b733c1d55ada33
train
show_examples
Run through some simple examples
barnum/gen_data.py
def show_examples(): """ Run through some simple examples """ first, last = create_name() add = create_street() zip, city, state = create_city_state_zip() phone = create_phone(zip) print(first, last) print(add) print("{0:s} {1:s} {2:s}".format(city, state, zip)) print(phone) ...
def show_examples(): """ Run through some simple examples """ first, last = create_name() add = create_street() zip, city, state = create_city_state_zip() phone = create_phone(zip) print(first, last) print(add) print("{0:s} {1:s} {2:s}".format(city, state, zip)) print(phone) ...
[ "Run", "through", "some", "simple", "examples" ]
chris1610/barnum-proj
python
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gen_data.py#L229-L249
[ "def", "show_examples", "(", ")", ":", "first", ",", "last", "=", "create_name", "(", ")", "add", "=", "create_street", "(", ")", "zip", ",", "city", ",", "state", "=", "create_city_state_zip", "(", ")", "phone", "=", "create_phone", "(", "zip", ")", "...
0a38f24bde66373553d02fbf67b733c1d55ada33
train
convert_to_mosek_index
MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA.
ncpol2sdpa/mosek_utils.py
def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row): """MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA. """ block_index, i, j = con...
def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row): """MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA. """ block_index, i, j = con...
[ "MOSEK", "requires", "a", "specific", "sparse", "format", "to", "define", "the", "lower", "-", "triangular", "part", "of", "a", "symmetric", "matrix", ".", "This", "function", "does", "the", "conversion", "from", "the", "sparse", "upper", "triangular", "matrix...
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/mosek_utils.py#L102-L113
[ "def", "convert_to_mosek_index", "(", "block_struct", ",", "row_offsets", ",", "block_offsets", ",", "row", ")", ":", "block_index", ",", "i", ",", "j", "=", "convert_row_to_sdpa_index", "(", "block_struct", ",", "row_offsets", ",", "row", ")", "offset", "=", ...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
convert_to_mosek_matrix
Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices.
ncpol2sdpa/mosek_utils.py
def convert_to_mosek_matrix(sdp): """Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices. """ barci = [] barcj = [] barcval = [] barai = [] baraj = [] baraval = [] for k in range(sdp.n_vars): barai.append([]) baraj.appe...
def convert_to_mosek_matrix(sdp): """Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices. """ barci = [] barcj = [] barcval = [] barai = [] baraj = [] baraval = [] for k in range(sdp.n_vars): barai.append([]) baraj.appe...
[ "Converts", "the", "entire", "sparse", "representation", "of", "the", "Fi", "constraint", "matrices", "to", "sparse", "MOSEK", "matrices", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/mosek_utils.py#L116-L155
[ "def", "convert_to_mosek_matrix", "(", "sdp", ")", ":", "barci", "=", "[", "]", "barcj", "=", "[", "]", "barcval", "=", "[", "]", "barai", "=", "[", "]", "baraj", "=", "[", "]", "baraval", "=", "[", "]", "for", "k", "in", "range", "(", "sdp", "...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
convert_to_mosek
Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`.
ncpol2sdpa/mosek_utils.py
def convert_to_mosek(sdp): """Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`. """ import mosek # Cheat when variables are complex and convert with PICOS if sdp.complex_matrix: ...
def convert_to_mosek(sdp): """Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`. """ import mosek # Cheat when variables are complex and convert with PICOS if sdp.complex_matrix: ...
[ "Convert", "an", "SDP", "relaxation", "to", "a", "MOSEK", "task", "." ]
peterwittek/ncpol2sdpa
python
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/mosek_utils.py#L158-L208
[ "def", "convert_to_mosek", "(", "sdp", ")", ":", "import", "mosek", "# Cheat when variables are complex and convert with PICOS", "if", "sdp", ".", "complex_matrix", ":", "from", ".", "picos_utils", "import", "convert_to_picos", "Problem", "=", "convert_to_picos", "(", "...
bce75d524d0b9d0093f32e3a0a5611f8589351a7
train
ANSIColorParser._add_text
If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there are no pending nodes.
docs/ansi.py
def _add_text(self, text): """ If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there are no pending nodes. """ if text: if self.pending_nodes: self.pending_nodes[-1].app...
def _add_text(self, text): """ If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there are no pending nodes. """ if text: if self.pending_nodes: self.pending_nodes[-1].app...
[ "If", "text", "is", "not", "empty", "append", "a", "new", "Text", "node", "to", "the", "most", "recent", "pending", "node", "if", "there", "is", "any", "or", "to", "the", "new", "nodes", "if", "there", "are", "no", "pending", "nodes", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/docs/ansi.py#L96-L106
[ "def", "_add_text", "(", "self", ",", "text", ")", ":", "if", "text", ":", "if", "self", ".", "pending_nodes", ":", "self", ".", "pending_nodes", "[", "-", "1", "]", ".", "append", "(", "nodes", ".", "Text", "(", "text", ")", ")", "else", ":", "s...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
version
Return version string.
setup.py
def version(): """Return version string.""" with open(os.path.join('curtsies', '__init__.py')) as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
def version(): """Return version string.""" with open(os.path.join('curtsies', '__init__.py')) as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
[ "Return", "version", "string", "." ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/setup.py#L6-L11
[ "def", "version", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "'curtsies'", ",", "'__init__.py'", ")", ")", "as", "input_file", ":", "for", "line", "in", "input_file", ":", "if", "line", ".", "startswith", "(", "'__version_...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
fsarray
fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the strings are of length greater than this width
curtsies/formatstringarray.py
def fsarray(strings, *args, **kwargs): """fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the str...
def fsarray(strings, *args, **kwargs): """fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the str...
[ "fsarray", "(", "list_of_FmtStrs_or_strings", "width", "=", "None", ")", "-", ">", "FSArray" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstringarray.py#L40-L60
[ "def", "fsarray", "(", "strings", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "strings", "=", "list", "(", "strings", ")", "if", "'width'", "in", "kwargs", ":", "width", "=", "kwargs", "[", "'width'", "]", "del", "kwargs", "[", "'width'", ...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
FSArray.diff
Returns two FSArrays with differences underlined
curtsies/formatstringarray.py
def diff(cls, a, b, ignore_formatting=False): """Returns two FSArrays with differences underlined""" def underline(x): return u'\x1b[4m%s\x1b[0m' % (x,) def blink(x): return u'\x1b[5m%s\x1b[0m' % (x,) a_rows = [] b_rows = [] max_width = max([len(row) for row in a] + [len(...
def diff(cls, a, b, ignore_formatting=False): """Returns two FSArrays with differences underlined""" def underline(x): return u'\x1b[4m%s\x1b[0m' % (x,) def blink(x): return u'\x1b[5m%s\x1b[0m' % (x,) a_rows = [] b_rows = [] max_width = max([len(row) for row in a] + [len(...
[ "Returns", "two", "FSArrays", "with", "differences", "underlined" ]
bpython/curtsies
python
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstringarray.py#L139-L171
[ "def", "diff", "(", "cls", ",", "a", ",", "b", ",", "ignore_formatting", "=", "False", ")", ":", "def", "underline", "(", "x", ")", ":", "return", "u'\\x1b[4m%s\\x1b[0m'", "%", "(", "x", ",", ")", "def", "blink", "(", "x", ")", ":", "return", "u'\\...
223e42b97fbf6c86b479ed4f0963a067333c5a63
train
Order.create
create new order function :param rate: float :param amount: float :param order_type: str; set 'buy' or 'sell' :param pair: str; set 'btc_jpy'
coincheck/order.py
def create(self,rate, amount, order_type, pair): ''' create new order function :param rate: float :param amount: float :param order_type: str; set 'buy' or 'sell' :param pair: str; set 'btc_jpy' ''' nonce = nounce() payload = { 'rate': rate, ...
def create(self,rate, amount, order_type, pair): ''' create new order function :param rate: float :param amount: float :param order_type: str; set 'buy' or 'sell' :param pair: str; set 'btc_jpy' ''' nonce = nounce() payload = { 'rate': rate, ...
[ "create", "new", "order", "function", ":", "param", "rate", ":", "float", ":", "param", "amount", ":", "float", ":", "param", "order_type", ":", "str", ";", "set", "buy", "or", "sell", ":", "param", "pair", ":", "str", ";", "set", "btc_jpy" ]
kmn/coincheck
python
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/order.py#L20-L43
[ "def", "create", "(", "self", ",", "rate", ",", "amount", ",", "order_type", ",", "pair", ")", ":", "nonce", "=", "nounce", "(", ")", "payload", "=", "{", "'rate'", ":", "rate", ",", "'amount'", ":", "amount", ",", "'order_type'", ":", "order_type", ...
4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc
train
Order.cancel
cancel the specified order :param order_id: order_id to be canceled
coincheck/order.py
def cancel(self,order_id): ''' cancel the specified order :param order_id: order_id to be canceled ''' url= 'https://coincheck.com/api/exchange/orders/' + order_id headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.delete(url,hea...
def cancel(self,order_id): ''' cancel the specified order :param order_id: order_id to be canceled ''' url= 'https://coincheck.com/api/exchange/orders/' + order_id headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.delete(url,hea...
[ "cancel", "the", "specified", "order", ":", "param", "order_id", ":", "order_id", "to", "be", "canceled" ]
kmn/coincheck
python
https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/order.py#L59-L66
[ "def", "cancel", "(", "self", ",", "order_id", ")", ":", "url", "=", "'https://coincheck.com/api/exchange/orders/'", "+", "order_id", "headers", "=", "make_header", "(", "url", ",", "access_key", "=", "self", ".", "access_key", ",", "secret_key", "=", "self", ...
4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc