repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
peterwittek/ncpol2sdpa | ncpol2sdpa/solver_common.py | get_sos_decomposition | def get_sos_decomposition(sdp, y_mat=None, threshold=0.0):
"""Given a solution of the dual problem, it returns the SOS
decomposition.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param y_mat: Optional parameter providing the dual solution of the
... | python | def get_sos_decomposition(sdp, y_mat=None, threshold=0.0):
"""Given a solution of the dual problem, it returns the SOS
decomposition.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param y_mat: Optional parameter providing the dual solution of the
... | [
"def",
"get_sos_decomposition",
"(",
"sdp",
",",
"y_mat",
"=",
"None",
",",
"threshold",
"=",
"0.0",
")",
":",
"if",
"len",
"(",
"sdp",
".",
"monomial_sets",
")",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"\"Cannot automatically match primal and dual \"",
"+"... | Given a solution of the dual problem, it returns the SOS
decomposition.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param y_mat: Optional parameter providing the dual solution of the
moment matrix. If not provided, the solution is extracted
... | [
"Given",
"a",
"solution",
"of",
"the",
"dual",
"problem",
"it",
"returns",
"the",
"SOS",
"decomposition",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L184-L236 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/solver_common.py | extract_dual_value | def extract_dual_value(sdp, monomial, blocks=None):
"""Given a solution of the dual problem and a monomial, it returns the
inner product of the corresponding coefficient matrix and the dual
solution. It can be restricted to certain blocks.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sd... | python | def extract_dual_value(sdp, monomial, blocks=None):
"""Given a solution of the dual problem and a monomial, it returns the
inner product of the corresponding coefficient matrix and the dual
solution. It can be restricted to certain blocks.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sd... | [
"def",
"extract_dual_value",
"(",
"sdp",
",",
"monomial",
",",
"blocks",
"=",
"None",
")",
":",
"if",
"sdp",
".",
"status",
"==",
"\"unsolved\"",
":",
"raise",
"Exception",
"(",
"\"The SDP relaxation is unsolved!\"",
")",
"if",
"blocks",
"is",
"None",
":",
"... | Given a solution of the dual problem and a monomial, it returns the
inner product of the corresponding coefficient matrix and the dual
solution. It can be restricted to certain blocks.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param monomial: The monomial for which the va... | [
"Given",
"a",
"solution",
"of",
"the",
"dual",
"problem",
"and",
"a",
"monomial",
"it",
"returns",
"the",
"inner",
"product",
"of",
"the",
"corresponding",
"coefficient",
"matrix",
"and",
"the",
"dual",
"solution",
".",
"It",
"can",
"be",
"restricted",
"to",... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L344-L386 | train |
chris1610/barnum-proj | barnum/gencc.py | completed_number | def completed_number(prefix, length):
"""
'prefix' is the start of the CC number as a string, any number of digits.
'length' is the length of the CC number to generate. Typically 13 or 16
"""
ccnumber = prefix
# generate digits
while len(ccnumber) < (length - 1):
digit = random.choic... | python | def completed_number(prefix, length):
"""
'prefix' is the start of the CC number as a string, any number of digits.
'length' is the length of the CC number to generate. Typically 13 or 16
"""
ccnumber = prefix
# generate digits
while len(ccnumber) < (length - 1):
digit = random.choic... | [
"def",
"completed_number",
"(",
"prefix",
",",
"length",
")",
":",
"ccnumber",
"=",
"prefix",
"# generate digits",
"while",
"len",
"(",
"ccnumber",
")",
"<",
"(",
"length",
"-",
"1",
")",
":",
"digit",
"=",
"random",
".",
"choice",
"(",
"[",
"'0'",
","... | 'prefix' is the start of the CC number as a string, any number of digits.
'length' is the length of the CC number to generate. Typically 13 or 16 | [
"prefix",
"is",
"the",
"start",
"of",
"the",
"CC",
"number",
"as",
"a",
"string",
"any",
"number",
"of",
"digits",
".",
"length",
"is",
"the",
"length",
"of",
"the",
"CC",
"number",
"to",
"generate",
".",
"Typically",
"13",
"or",
"16"
] | 0a38f24bde66373553d02fbf67b733c1d55ada33 | https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gencc.py#L63-L90 | train |
laike9m/ezcf | ezcf/type_json.py | JsonLoader.load_module | def load_module(self, fullname):
"""
load_module is always called with the same argument as finder's
find_module, see "How Import Works"
"""
mod = super(JsonLoader, self).load_module(fullname)
try:
with codecs.open(self.cfg_file, 'r', 'utf-8') as f:
... | python | def load_module(self, fullname):
"""
load_module is always called with the same argument as finder's
find_module, see "How Import Works"
"""
mod = super(JsonLoader, self).load_module(fullname)
try:
with codecs.open(self.cfg_file, 'r', 'utf-8') as f:
... | [
"def",
"load_module",
"(",
"self",
",",
"fullname",
")",
":",
"mod",
"=",
"super",
"(",
"JsonLoader",
",",
"self",
")",
".",
"load_module",
"(",
"fullname",
")",
"try",
":",
"with",
"codecs",
".",
"open",
"(",
"self",
".",
"cfg_file",
",",
"'r'",
","... | load_module is always called with the same argument as finder's
find_module, see "How Import Works" | [
"load_module",
"is",
"always",
"called",
"with",
"the",
"same",
"argument",
"as",
"finder",
"s",
"find_module",
"see",
"How",
"Import",
"Works"
] | 30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12 | https://github.com/laike9m/ezcf/blob/30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12/ezcf/type_json.py#L32-L53 | train |
bpython/curtsies | examples/gameexample.py | World.process_event | def process_event(self, c):
"""Returns a message from tick() to be displayed if game is over"""
if c == "":
sys.exit()
elif c in key_directions:
self.move_entity(self.player, *vscale(self.player.speed, key_directions[c]))
else:
return "try arrow keys,... | python | def process_event(self, c):
"""Returns a message from tick() to be displayed if game is over"""
if c == "":
sys.exit()
elif c in key_directions:
self.move_entity(self.player, *vscale(self.player.speed, key_directions[c]))
else:
return "try arrow keys,... | [
"def",
"process_event",
"(",
"self",
",",
"c",
")",
":",
"if",
"c",
"==",
"\"\u0004\"",
":",
"sys",
".",
"exit",
"(",
")",
"elif",
"c",
"in",
"key_directions",
":",
"self",
".",
"move_entity",
"(",
"self",
".",
"player",
",",
"*",
"vscale",
"(",
"s... | Returns a message from tick() to be displayed if game is over | [
"Returns",
"a",
"message",
"from",
"tick",
"()",
"to",
"be",
"displayed",
"if",
"game",
"is",
"over"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/gameexample.py#L57-L65 | train |
bpython/curtsies | examples/gameexample.py | World.tick | def tick(self):
"""Returns a message to be displayed if game is over, else None"""
for npc in self.npcs:
self.move_entity(npc, *npc.towards(self.player))
for entity1, entity2 in itertools.combinations(self.entities, 2):
if (entity1.x, entity1.y) == (entity2.x, entity2.y):... | python | def tick(self):
"""Returns a message to be displayed if game is over, else None"""
for npc in self.npcs:
self.move_entity(npc, *npc.towards(self.player))
for entity1, entity2 in itertools.combinations(self.entities, 2):
if (entity1.x, entity1.y) == (entity2.x, entity2.y):... | [
"def",
"tick",
"(",
"self",
")",
":",
"for",
"npc",
"in",
"self",
".",
"npcs",
":",
"self",
".",
"move_entity",
"(",
"npc",
",",
"*",
"npc",
".",
"towards",
"(",
"self",
".",
"player",
")",
")",
"for",
"entity1",
",",
"entity2",
"in",
"itertools",
... | Returns a message to be displayed if game is over, else None | [
"Returns",
"a",
"message",
"to",
"be",
"displayed",
"if",
"game",
"is",
"over",
"else",
"None"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/gameexample.py#L67-L83 | train |
bpython/curtsies | curtsies/window.py | BaseWindow.array_from_text | def array_from_text(self, msg):
"""Returns a FSArray of the size of the window containing msg"""
rows, columns = self.t.height, self.t.width
return self.array_from_text_rc(msg, rows, columns) | python | def array_from_text(self, msg):
"""Returns a FSArray of the size of the window containing msg"""
rows, columns = self.t.height, self.t.width
return self.array_from_text_rc(msg, rows, columns) | [
"def",
"array_from_text",
"(",
"self",
",",
"msg",
")",
":",
"rows",
",",
"columns",
"=",
"self",
".",
"t",
".",
"height",
",",
"self",
".",
"t",
".",
"width",
"return",
"self",
".",
"array_from_text_rc",
"(",
"msg",
",",
"rows",
",",
"columns",
")"
... | Returns a FSArray of the size of the window containing msg | [
"Returns",
"a",
"FSArray",
"of",
"the",
"size",
"of",
"the",
"window",
"containing",
"msg"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L76-L79 | train |
bpython/curtsies | curtsies/window.py | FullscreenWindow.render_to_terminal | def render_to_terminal(self, array, cursor_pos=(0, 0)):
"""Renders array to terminal and places (0-indexed) cursor
Args:
array (FSArray): Grid of styled characters to be rendered.
* If array received is of width too small, render it anyway
* If array received is of width to... | python | def render_to_terminal(self, array, cursor_pos=(0, 0)):
"""Renders array to terminal and places (0-indexed) cursor
Args:
array (FSArray): Grid of styled characters to be rendered.
* If array received is of width too small, render it anyway
* If array received is of width to... | [
"def",
"render_to_terminal",
"(",
"self",
",",
"array",
",",
"cursor_pos",
"=",
"(",
"0",
",",
"0",
")",
")",
":",
"# TODO there's a race condition here - these height and widths are",
"# super fresh - they might change between the array being constructed",
"# and rendered",
"#... | Renders array to terminal and places (0-indexed) cursor
Args:
array (FSArray): Grid of styled characters to be rendered.
* If array received is of width too small, render it anyway
* If array received is of width too large,
* render the renderable portion
* If array... | [
"Renders",
"array",
"to",
"terminal",
"and",
"places",
"(",
"0",
"-",
"indexed",
")",
"cursor"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L144-L204 | train |
bpython/curtsies | curtsies/window.py | CursorAwareWindow.get_cursor_position | def get_cursor_position(self):
"""Returns the terminal (row, column) of the cursor
0-indexed, like blessings cursor positions"""
# TODO would this be cleaner as a parameter?
in_stream = self.in_stream
query_cursor_position = u"\x1b[6n"
self.write(query_cursor_position)
... | python | def get_cursor_position(self):
"""Returns the terminal (row, column) of the cursor
0-indexed, like blessings cursor positions"""
# TODO would this be cleaner as a parameter?
in_stream = self.in_stream
query_cursor_position = u"\x1b[6n"
self.write(query_cursor_position)
... | [
"def",
"get_cursor_position",
"(",
"self",
")",
":",
"# TODO would this be cleaner as a parameter?",
"in_stream",
"=",
"self",
".",
"in_stream",
"query_cursor_position",
"=",
"u\"\\x1b[6n\"",
"self",
".",
"write",
"(",
"query_cursor_position",
")",
"def",
"retrying_read",... | Returns the terminal (row, column) of the cursor
0-indexed, like blessings cursor positions | [
"Returns",
"the",
"terminal",
"(",
"row",
"column",
")",
"of",
"the",
"cursor"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L271-L318 | train |
bpython/curtsies | curtsies/window.py | CursorAwareWindow.get_cursor_vertical_diff | def get_cursor_vertical_diff(self):
"""Returns the how far down the cursor moved since last render.
Note:
If another get_cursor_vertical_diff call is already in progress,
immediately returns zero. (This situation is likely if
get_cursor_vertical_diff is called from a... | python | def get_cursor_vertical_diff(self):
"""Returns the how far down the cursor moved since last render.
Note:
If another get_cursor_vertical_diff call is already in progress,
immediately returns zero. (This situation is likely if
get_cursor_vertical_diff is called from a... | [
"def",
"get_cursor_vertical_diff",
"(",
"self",
")",
":",
"# Probably called by a SIGWINCH handler, and therefore",
"# will do cursor querying until a SIGWINCH doesn't happen during",
"# the query. Calls to the function from a signal handler COULD STILL",
"# HAPPEN out of order -",
"# they just ... | Returns the how far down the cursor moved since last render.
Note:
If another get_cursor_vertical_diff call is already in progress,
immediately returns zero. (This situation is likely if
get_cursor_vertical_diff is called from a SIGWINCH signal
handler, since sig... | [
"Returns",
"the",
"how",
"far",
"down",
"the",
"cursor",
"moved",
"since",
"last",
"render",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L320-L347 | train |
bpython/curtsies | curtsies/window.py | CursorAwareWindow._get_cursor_vertical_diff_once | def _get_cursor_vertical_diff_once(self):
"""Returns the how far down the cursor moved."""
old_top_usable_row = self.top_usable_row
row, col = self.get_cursor_position()
if self._last_cursor_row is None:
cursor_dy = 0
else:
cursor_dy = row - self._last_cur... | python | def _get_cursor_vertical_diff_once(self):
"""Returns the how far down the cursor moved."""
old_top_usable_row = self.top_usable_row
row, col = self.get_cursor_position()
if self._last_cursor_row is None:
cursor_dy = 0
else:
cursor_dy = row - self._last_cur... | [
"def",
"_get_cursor_vertical_diff_once",
"(",
"self",
")",
":",
"old_top_usable_row",
"=",
"self",
".",
"top_usable_row",
"row",
",",
"col",
"=",
"self",
".",
"get_cursor_position",
"(",
")",
"if",
"self",
".",
"_last_cursor_row",
"is",
"None",
":",
"cursor_dy",... | Returns the how far down the cursor moved. | [
"Returns",
"the",
"how",
"far",
"down",
"the",
"cursor",
"moved",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L349-L368 | train |
bpython/curtsies | curtsies/window.py | CursorAwareWindow.render_to_terminal | def render_to_terminal(self, array, cursor_pos=(0, 0)):
"""Renders array to terminal, returns the number of lines scrolled offscreen
Returns:
Number of times scrolled
Args:
array (FSArray): Grid of styled characters to be rendered.
If array received is of wid... | python | def render_to_terminal(self, array, cursor_pos=(0, 0)):
"""Renders array to terminal, returns the number of lines scrolled offscreen
Returns:
Number of times scrolled
Args:
array (FSArray): Grid of styled characters to be rendered.
If array received is of wid... | [
"def",
"render_to_terminal",
"(",
"self",
",",
"array",
",",
"cursor_pos",
"=",
"(",
"0",
",",
"0",
")",
")",
":",
"for_stdout",
"=",
"self",
".",
"fmtstr_to_stdout_xform",
"(",
")",
"# caching of write and tc (avoiding the self. lookups etc) made",
"# no significant ... | Renders array to terminal, returns the number of lines scrolled offscreen
Returns:
Number of times scrolled
Args:
array (FSArray): Grid of styled characters to be rendered.
If array received is of width too small, render it anyway
if array received is of... | [
"Renders",
"array",
"to",
"terminal",
"returns",
"the",
"number",
"of",
"lines",
"scrolled",
"offscreen"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L370-L461 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | Relaxation.solve | def solve(self, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices. It also sets these values in the `sdpRelaxation` object,
along with some status informa... | python | def solve(self, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices. It also sets these values in the `sdpRelaxation` object,
along with some status informa... | [
"def",
"solve",
"(",
"self",
",",
"solver",
"=",
"None",
",",
"solverparameters",
"=",
"None",
")",
":",
"if",
"self",
".",
"F",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Relaxation is not generated yet. Call \"",
"\"'SdpRelaxation.get_relaxation' first\"",
... | Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices. It also sets these values in the `sdpRelaxation` object,
along with some status information.
:param sdpRelaxation: The SDP relaxation to be so... | [
"Call",
"a",
"solver",
"on",
"the",
"SDP",
"relaxation",
".",
"Upon",
"successful",
"solution",
"it",
"returns",
"the",
"primal",
"and",
"dual",
"objective",
"values",
"along",
"with",
"the",
"solution",
"matrices",
".",
"It",
"also",
"sets",
"these",
"value... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L65-L109 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation._process_monomial | def _process_monomial(self, monomial, n_vars):
"""Process a single monomial when building the moment matrix.
"""
processed_monomial, coeff = separate_scalar_factor(monomial)
# Are we substituting this moment?
try:
substitute = self.moment_substitutions[processed_monom... | python | def _process_monomial(self, monomial, n_vars):
"""Process a single monomial when building the moment matrix.
"""
processed_monomial, coeff = separate_scalar_factor(monomial)
# Are we substituting this moment?
try:
substitute = self.moment_substitutions[processed_monom... | [
"def",
"_process_monomial",
"(",
"self",
",",
"monomial",
",",
"n_vars",
")",
":",
"processed_monomial",
",",
"coeff",
"=",
"separate_scalar_factor",
"(",
"monomial",
")",
"# Are we substituting this moment?",
"try",
":",
"substitute",
"=",
"self",
".",
"moment_subs... | Process a single monomial when building the moment matrix. | [
"Process",
"a",
"single",
"monomial",
"when",
"building",
"the",
"moment",
"matrix",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L269-L322 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation._generate_moment_matrix | def _generate_moment_matrix(self, n_vars, block_index, processed_entries,
monomialsA, monomialsB, ppt=False):
"""Generate the moment matrix of monomials.
Arguments:
n_vars -- current number of variables
block_index -- current block index in the SDP matrix... | python | def _generate_moment_matrix(self, n_vars, block_index, processed_entries,
monomialsA, monomialsB, ppt=False):
"""Generate the moment matrix of monomials.
Arguments:
n_vars -- current number of variables
block_index -- current block index in the SDP matrix... | [
"def",
"_generate_moment_matrix",
"(",
"self",
",",
"n_vars",
",",
"block_index",
",",
"processed_entries",
",",
"monomialsA",
",",
"monomialsB",
",",
"ppt",
"=",
"False",
")",
":",
"row_offset",
"=",
"0",
"if",
"block_index",
">",
"0",
":",
"for",
"block_si... | Generate the moment matrix of monomials.
Arguments:
n_vars -- current number of variables
block_index -- current block index in the SDP matrix
monomials -- |W_d| set of words of length up to the relaxation level | [
"Generate",
"the",
"moment",
"matrix",
"of",
"monomials",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L359-L433 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation._get_index_of_monomial | def _get_index_of_monomial(self, element, enablesubstitution=True,
daggered=False):
"""Returns the index of a monomial.
"""
result = []
processed_element, coeff1 = separate_scalar_factor(element)
if processed_element in self.moment_substitutions:
... | python | def _get_index_of_monomial(self, element, enablesubstitution=True,
daggered=False):
"""Returns the index of a monomial.
"""
result = []
processed_element, coeff1 = separate_scalar_factor(element)
if processed_element in self.moment_substitutions:
... | [
"def",
"_get_index_of_monomial",
"(",
"self",
",",
"element",
",",
"enablesubstitution",
"=",
"True",
",",
"daggered",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"processed_element",
",",
"coeff1",
"=",
"separate_scalar_factor",
"(",
"element",
")",
"if"... | Returns the index of a monomial. | [
"Returns",
"the",
"index",
"of",
"a",
"monomial",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L463-L511 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation.__push_facvar_sparse | def __push_facvar_sparse(self, polynomial, block_index, row_offset, i, j):
"""Calculate the sparse vector representation of a polynomial
and pushes it to the F structure.
"""
width = self.block_struct[block_index - 1]
# Preprocess the polynomial for uniform handling later
... | python | def __push_facvar_sparse(self, polynomial, block_index, row_offset, i, j):
"""Calculate the sparse vector representation of a polynomial
and pushes it to the F structure.
"""
width = self.block_struct[block_index - 1]
# Preprocess the polynomial for uniform handling later
... | [
"def",
"__push_facvar_sparse",
"(",
"self",
",",
"polynomial",
",",
"block_index",
",",
"row_offset",
",",
"i",
",",
"j",
")",
":",
"width",
"=",
"self",
".",
"block_struct",
"[",
"block_index",
"-",
"1",
"]",
"# Preprocess the polynomial for uniform handling late... | Calculate the sparse vector representation of a polynomial
and pushes it to the F structure. | [
"Calculate",
"the",
"sparse",
"vector",
"representation",
"of",
"a",
"polynomial",
"and",
"pushes",
"it",
"to",
"the",
"F",
"structure",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L513-L534 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation._get_facvar | def _get_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] * (self.n_var... | python | def _get_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] * (self.n_var... | [
"def",
"_get_facvar",
"(",
"self",
",",
"polynomial",
")",
":",
"facvar",
"=",
"[",
"0",
"]",
"*",
"(",
"self",
".",
"n_vars",
"+",
"1",
")",
"# Preprocess the polynomial for uniform handling later",
"if",
"is_number_type",
"(",
"polynomial",
")",
":",
"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. | [
"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... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L536-L556 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation.__process_inequalities | def __process_inequalities(self, block_index):
"""Generate localizing matrices
Arguments:
inequalities -- list of inequality constraints
monomials -- localizing monomials
block_index -- the current block index in constraint matrices of the
SDP relaxatio... | python | def __process_inequalities(self, block_index):
"""Generate localizing matrices
Arguments:
inequalities -- list of inequality constraints
monomials -- localizing monomials
block_index -- the current block index in constraint matrices of the
SDP relaxatio... | [
"def",
"__process_inequalities",
"(",
"self",
",",
"block_index",
")",
":",
"initial_block_index",
"=",
"block_index",
"row_offsets",
"=",
"[",
"0",
"]",
"for",
"block",
",",
"block_size",
"in",
"enumerate",
"(",
"self",
".",
"block_struct",
")",
":",
"row_off... | Generate localizing matrices
Arguments:
inequalities -- list of inequality constraints
monomials -- localizing monomials
block_index -- the current block index in constraint matrices of the
SDP relaxation | [
"Generate",
"localizing",
"matrices"
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L558-L620 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation.__process_equalities | def __process_equalities(self, equalities, momentequalities):
"""Generate localizing matrices
Arguments:
equalities -- list of equality constraints
equalities -- list of moment equality constraints
"""
monomial_sets = []
n_rows = 0
le = 0
if equal... | python | def __process_equalities(self, equalities, momentequalities):
"""Generate localizing matrices
Arguments:
equalities -- list of equality constraints
equalities -- list of moment equality constraints
"""
monomial_sets = []
n_rows = 0
le = 0
if equal... | [
"def",
"__process_equalities",
"(",
"self",
",",
"equalities",
",",
"momentequalities",
")",
":",
"monomial_sets",
"=",
"[",
"]",
"n_rows",
"=",
"0",
"le",
"=",
"0",
"if",
"equalities",
"is",
"not",
"None",
":",
"for",
"equality",
"in",
"equalities",
":",
... | Generate localizing matrices
Arguments:
equalities -- list of equality constraints
equalities -- list of moment equality constraints | [
"Generate",
"localizing",
"matrices"
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L622-L694 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation.__remove_equalities | def __remove_equalities(self, equalities, momentequalities):
"""Attempt to remove equalities by solving the linear equations.
"""
A = self.__process_equalities(equalities, momentequalities)
if min(A.shape != np.linalg.matrix_rank(A)):
print("Warning: equality constraints are ... | python | def __remove_equalities(self, equalities, momentequalities):
"""Attempt to remove equalities by solving the linear equations.
"""
A = self.__process_equalities(equalities, momentequalities)
if min(A.shape != np.linalg.matrix_rank(A)):
print("Warning: equality constraints are ... | [
"def",
"__remove_equalities",
"(",
"self",
",",
"equalities",
",",
"momentequalities",
")",
":",
"A",
"=",
"self",
".",
"__process_equalities",
"(",
"equalities",
",",
"momentequalities",
")",
"if",
"min",
"(",
"A",
".",
"shape",
"!=",
"np",
".",
"linalg",
... | Attempt to remove equalities by solving the linear equations. | [
"Attempt",
"to",
"remove",
"equalities",
"by",
"solving",
"the",
"linear",
"equations",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L696-L729 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation._calculate_block_structure | def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_struct=None):
"""Calculates the block_struct array for the outp... | python | 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",
")",
":",
"if",
"block_struct",
"is",
"... | Calculates the block_struct array for the output file. | [
"Calculates",
"the",
"block_struct",
"array",
"for",
"the",
"output",
"file",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L843-L935 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation.process_constraints | def process_constraints(self, inequalities=None, equalities=None,
momentinequalities=None, momentequalities=None,
block_index=0, removeequalities=False):
"""Process the constraints and generate localizing matrices. Useful
only if the moment matrix ... | python | def process_constraints(self, inequalities=None, equalities=None,
momentinequalities=None, momentequalities=None,
block_index=0, removeequalities=False):
"""Process the constraints and generate localizing matrices. Useful
only if the moment matrix ... | [
"def",
"process_constraints",
"(",
"self",
",",
"inequalities",
"=",
"None",
",",
"equalities",
"=",
"None",
",",
"momentinequalities",
"=",
"None",
",",
"momentequalities",
"=",
"None",
",",
"block_index",
"=",
"0",
",",
"removeequalities",
"=",
"False",
")",... | Process the constraints and generate localizing matrices. Useful
only if the moment matrix already exists. Call it if you want to
replace your constraints. The number of the respective types of
constraints and the maximum degree of each constraint must remain the
same.
:param in... | [
"Process",
"the",
"constraints",
"and",
"generate",
"localizing",
"matrices",
".",
"Useful",
"only",
"if",
"the",
"moment",
"matrix",
"already",
"exists",
".",
"Call",
"it",
"if",
"you",
"want",
"to",
"replace",
"your",
"constraints",
".",
"The",
"number",
"... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1007-L1074 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation.set_objective | 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 ... | python | 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",
")",
":",
"if",
"objective",
"is",
"not",
"None",
":",
"facvar",
"=",
"self",
".",
"_get_facvar",
"(",
"simplify_polynomial",
"(",
"objective",
",",
"self",
".",
"subs... | 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... | [
"Set",
"or",
"change",
"the",
"objective",
"function",
"of",
"the",
"polynomial",
"optimization",
"problem",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1076-L1120 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation.find_solution_ranks | 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
... | python | 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",
")",
":",
"return",
"find_solution_ranks",
"(",
"self",
",",
"xmat",
"=",
"xmat",
",",
"baselevel",
"=",
"baselevel",
")"
] | 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 ... | [
"Helper",
"function",
"to",
"detect",
"rank",
"loop",
"in",
"the",
"solution",
"matrix",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1167-L1183 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation.get_dual | 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... | python | 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",
")",
":",
"if",
"not",
"isinstance",
"(",
"constraint",
",",
"Expr",
")",
":",
"raise",
"Exception",
"(",
"\"Not a monomial or polynomial!\"",
")",
"elif",
"self",
".",
"status",
... | 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... | [
"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"... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1185-L1212 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation.write_to_file | 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.
... | python | 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",
")",
":",
"if",
"filetype",
"==",
"\"sdpa\"",
"and",
"not",
"filename",
".",
"endswith",
"(",
"\".dat-s\"",
")",
":",
"raise",
"Exception",
"(",
"\"SDPA files must have .dat-s ... | 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... | [
"Write",
"the",
"relaxation",
"to",
"a",
"file",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1214-L1247 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdp_relaxation.py | SdpRelaxation.get_relaxation | def get_relaxation(self, level, objective=None, inequalities=None,
equalities=None, substitutions=None,
momentinequalities=None, momentequalities=None,
momentsubstitutions=None,
removeequalities=False, extramonomials=None,
... | python | 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",
"=",
"Non... | 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... | [
"Get",
"the",
"SDP",
"relaxation",
"of",
"a",
"noncommutative",
"polynomial",
"optimization",
"problem",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1290-L1434 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | flatten | 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... | python | 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",
")",
":",
"new_list",
"=",
"[",
"]",
"for",
"element",
"in",
"lol",
":",
"if",
"element",
"is",
"None",
":",
"continue",
"elif",
"not",
"isinstance",
"(",
"element",
",",
"list",
")",
"and",
"not",
"isinstance",
"(",
"el... | 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. | [
"Flatten",
"a",
"list",
"of",
"lists",
"to",
"a",
"list",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L16-L32 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | simplify_polynomial | 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)
... | python | 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",
")",
":",
"if",
"isinstance",
"(",
"polynomial",
",",
"(",
"int",
",",
"float",
",",
"complex",
")",
")",
":",
"return",
"polynomial",
"polynomial",
"=",
"(",
"1.0",
"*",
"polyno... | Simplify a polynomial for uniform handling later. | [
"Simplify",
"a",
"polynomial",
"for",
"uniform",
"handling",
"later",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L35-L54 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | __separate_scalar_factor | 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:
... | python | 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",
")",
":",
"scalar_factor",
"=",
"1",
"if",
"is_number_type",
"(",
"monomial",
")",
":",
"return",
"S",
".",
"One",
",",
"monomial",
"if",
"monomial",
"==",
"0",
":",
"return",
"S",
".",
"One",
",",
"0",... | Separate the constant factor from a monomial. | [
"Separate",
"the",
"constant",
"factor",
"from",
"a",
"monomial",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L81-L96 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | get_support | 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)
... | python | 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",
")",
":",
"support",
"=",
"[",
"]",
"if",
"is_number_type",
"(",
"polynomial",
")",
":",
"support",
".",
"append",
"(",
"[",
"0",
"]",
"*",
"len",
"(",
"variables",
")",
")",
"return",
"support... | Gets the support of a polynomial. | [
"Gets",
"the",
"support",
"of",
"a",
"polynomial",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L99-L121 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | get_support_variables | 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_... | python | 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",
")",
":",
"support",
"=",
"[",
"]",
"if",
"is_number_type",
"(",
"polynomial",
")",
":",
"return",
"support",
"for",
"monomial",
"in",
"polynomial",
".",
"expand",
"(",
")",
".",
"as_coefficients_dict",
"(",
... | Gets the support of a polynomial. | [
"Gets",
"the",
"support",
"of",
"a",
"polynomial",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L124-L143 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | separate_scalar_factor | 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... | python | 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",
")",
":",
"coeff",
"=",
"1.0",
"monomial",
"=",
"S",
".",
"One",
"if",
"isinstance",
"(",
"element",
",",
"(",
"int",
",",
"float",
",",
"complex",
")",
")",
":",
"coeff",
"*=",
"element",
"return",
"mon... | Construct a monomial with the coefficient separated
from an element in a polynomial. | [
"Construct",
"a",
"monomial",
"with",
"the",
"coefficient",
"separated",
"from",
"an",
"element",
"in",
"a",
"polynomial",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L146-L165 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | count_ncmonomials | 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... | python | 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",
")",
":",
"ncmoncount",
"=",
"0",
"for",
"monomial",
"in",
"monomials",
":",
"if",
"ncdegree",
"(",
"monomial",
")",
"<=",
"degree",
":",
"ncmoncount",
"+=",
"1",
"else",
":",
"break",
"return",
... | 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... | [
"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",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L168-L185 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | apply_substitutions | 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:
... | python | 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",
")",
":",
"if",
"is_number_type",
"(",
"monomial",
")",
":",
"return",
"monomial",
"original_monomial",
"=",
"monomial",
"changed",
"=",
"True",
"if",
"not",... | Helper function to remove monomials from the basis. | [
"Helper",
"function",
"to",
"remove",
"monomials",
"from",
"the",
"basis",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L188-L214 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | fast_substitute | 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... | python | 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",
")",
":",
"if",
"is_number_type",
"(",
"monomial",
")",
":",
"return",
"monomial",
"if",
"monomial",
".",
"is_Add",
":",
"return",
"sum",
"(",
"[",
"fast_substitute",
"(",
"element",
... | 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... | [
"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"... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L217-L352 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | generate_variables | 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... | python | 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",
")",
":",
"variables",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n_vars",
")",
":",
"if",
"n_vars",
">",
"1",
"... | 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.
... | [
"Generates",
"a",
"number",
"of",
"commutative",
"or",
"noncommutative",
"variables"
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L355-L395 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | generate_operators | 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-... | python | 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",
")",
":",
"variables",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n_vars",
")",
":",
"if",
"n_vars",
">",
"1",
... | 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.
... | [
"Generates",
"a",
"number",
"of",
"commutative",
"or",
"noncommutative",
"operators"
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L398-L434 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | get_monomials | 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... | python | 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",
")",
":",
"if",
"degree",
"==",
"-",
"1",
":",
"return",
"[",
"]",
"if",
"not",
"variables",
":",
"return",
"[",
"S",
".",
"One",
"]",
"else",
":",
"_variables",
"=",
"variables",
"[",
":",
"... | 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`.
:... | [
"Generates",
"all",
"noncommutative",
"monomials",
"up",
"to",
"a",
"degree"
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L437-L469 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | ncdegree | 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... | python | 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",
")",
":",
"degree",
"=",
"0",
"if",
"is_number_type",
"(",
"polynomial",
")",
":",
"return",
"degree",
"polynomial",
"=",
"polynomial",
".",
"expand",
"(",
")",
"for",
"monomial",
"in",
"polynomial",
".",
"as_coefficient... | 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. | [
"Returns",
"the",
"degree",
"of",
"a",
"noncommutative",
"polynomial",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L472-L493 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | iscomplex | 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)):... | python | 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",
")",
":",
"if",
"isinstance",
"(",
"polynomial",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"False",
"if",
"isinstance",
"(",
"polynomial",
",",
"complex",
")",
":",
"return",
"True",
"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. | [
"Returns",
"whether",
"the",
"polynomial",
"has",
"complex",
"coefficients"
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L496-L513 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | get_all_monomials | 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... | python | 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",
")",
":",
"monomials",
"=",
"get_monomials",
"(",
"variables",
",",
"degree",
")",
"if",
"extramonomials",
"is",
"n... | Return the monomials of a certain degree. | [
"Return",
"the",
"monomials",
"of",
"a",
"certain",
"degree",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L516-L530 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | pick_monomials_up_to_degree | 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... | python | 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",
")",
":",
"ordered_monomials",
"=",
"[",
"]",
"if",
"degree",
">=",
"0",
":",
"ordered_monomials",
".",
"append",
"(",
"S",
".",
"One",
")",
"for",
"deg",
"in",
"range",
"(",
"1",
","... | Collect monomials up to a given degree. | [
"Collect",
"monomials",
"up",
"to",
"a",
"given",
"degree",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L533-L541 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | pick_monomials_of_degree | 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 | python | 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",
")",
":",
"selected_monomials",
"=",
"[",
"]",
"for",
"monomial",
"in",
"monomials",
":",
"if",
"ncdegree",
"(",
"monomial",
")",
"==",
"degree",
":",
"selected_monomials",
".",
"append",
"(",... | Collect all monomials up of a given degree. | [
"Collect",
"all",
"monomials",
"up",
"of",
"a",
"given",
"degree",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L544-L551 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | save_monomial_index | 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... | python | 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",
")",
":",
"monomial_translation",
"=",
"[",
"''",
"]",
"*",
"(",
"len",
"(",
"monomial_index",
")",
"+",
"1",
")",
"for",
"key",
",",
"k",
"in",
"monomial_index",
".",
"items",
"(",
")... | 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",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L562-L577 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | unique | 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 | python | 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",
")",
":",
"seen",
"=",
"{",
"}",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"seq",
":",
"marker",
"=",
"item",
"if",
"marker",
"in",
"seen",
":",
"continue",
"seen",
"[",
"marker",
"]",
"=",
"1",
"result",
".",
"... | Helper function to include only unique monomials in a basis. | [
"Helper",
"function",
"to",
"include",
"only",
"unique",
"monomials",
"in",
"a",
"basis",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L580-L590 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | build_permutation_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 | python | 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",
")",
":",
"matrix",
"=",
"lil_matrix",
"(",
"(",
"len",
"(",
"permutation",
")",
",",
"len",
"(",
"permutation",
")",
")",
")",
"column",
"=",
"0",
"for",
"row",
"in",
"permutation",
":",
"matrix",
"... | Build a permutation matrix for a permutation. | [
"Build",
"a",
"permutation",
"matrix",
"for",
"a",
"permutation",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L593-L601 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/nc_utils.py | convert_relational | 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... | python | 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",
")",
":",
"rel",
"=",
"relational",
".",
"rel_op",
"if",
"rel",
"in",
"[",
"'=='",
",",
"'>='",
",",
"'>'",
"]",
":",
"return",
"relational",
".",
"lhs",
"-",
"relational",
".",
"rhs",
"elif",
"rel",
"in"... | Convert all inequalities to >=0 form. | [
"Convert",
"all",
"inequalities",
"to",
">",
"=",
"0",
"form",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/nc_utils.py#L604-L614 | train |
bpython/curtsies | examples/tictactoeexample.py | value | 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', '... | python | 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'",
")",
":",
"w",
"=",
"board",
".",
"winner",
"(",
")",
"if",
"w",
"==",
"who",
":",
"return",
"1",
"if",
"w",
"==",
"opp",
"(",
"who",
")",
":",
"return",
"-",
"1",
"if",
"board",
".",
"t... | 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', ' '], [' ', ' ', '... | [
"Returns",
"the",
"value",
"of",
"a",
"board",
">>>",
"b",
"=",
"Board",
"()",
";",
"b",
".",
"_rows",
"=",
"[[",
"x",
"x",
"x",
"]",
"[",
"x",
"x",
"x",
"]",
"[",
"x",
"x",
"x",
"]]",
">>>",
"value",
"(",
"b",
")",
"1",
">>>",
"b",
"=",
... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L68-L94 | train |
bpython/curtsies | examples/tictactoeexample.py | ai | 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] | python | 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'",
")",
":",
"return",
"sorted",
"(",
"board",
".",
"possible",
"(",
")",
",",
"key",
"=",
"lambda",
"b",
":",
"value",
"(",
"b",
",",
"who",
")",
")",
"[",
"-",
"1",
"]"
] | Returns best next board
>>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']]
>>> ai(b)
< Board |xo.xo.x..| > | [
"Returns",
"best",
"next",
"board"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L96-L104 | train |
bpython/curtsies | examples/tictactoeexample.py | Board.winner | 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 | python | 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",
")",
":",
"for",
"c",
"in",
"'xo'",
":",
"for",
"comb",
"in",
"[",
"(",
"0",
",",
"3",
",",
"6",
")",
",",
"(",
"1",
",",
"4",
",",
"7",
")",
",",
"(",
"2",
",",
"5",
",",
"8",
")",
",",
"(",
"0",
",",
... | Returns either x or o if one of them won, otherwise None | [
"Returns",
"either",
"x",
"or",
"o",
"if",
"one",
"of",
"them",
"won",
"otherwise",
"None"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L40-L46 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/faacets_relaxation.py | FaacetsRelaxation.get_relaxation | 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... | python | 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",
")",
":",
"coefficients",
"=",
"collinsgisin_to_faacets",
"(",
"I",
")",
"M",
",",
"ncIndices",
"=",
"get_faacets_moment_matrix",
"(",
"A_configuration",
",",
"B_config... | 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... | [
"Get",
"the",
"sparse",
"SDP",
"relaxation",
"of",
"a",
"Bell",
"inequality",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/faacets_relaxation.py#L63-L91 | train |
zeekay/soundcloud-cli | soundcloud_cli/api/share.py | share | 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... | python | 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",
")",
":",
"client",
"=",
"get_client",
"(",
")",
"if",
"url",
":",
"track_id",
"=",
"client",
".",
"get",
"(",
"'/resolve'",
",",
"url",
"=",
"url",
... | Returns list of users track has been shared with.
Either track or url need to be provided. | [
"Returns",
"list",
"of",
"users",
"track",
"has",
"been",
"shared",
"with",
".",
"Either",
"track",
"or",
"url",
"need",
"to",
"be",
"provided",
"."
] | 8a83013683e1acf32f093239bbb6d3c02bc50b37 | https://github.com/zeekay/soundcloud-cli/blob/8a83013683e1acf32f093239bbb6d3c02bc50b37/soundcloud_cli/api/share.py#L7-L34 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/picos_utils.py | solve_with_cvxopt | 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... | python | 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",
")",
":",
"P",
"=",
"convert_to_picos",
"(",
"sdp",
")",
"P",
".",
"set_option",
"(",
"\"solver\"",
",",
"\"cvxopt\"",
")",
"P",
".",
"set_option",
"(",
"\"verbose\"",
",",
"sdp"... | 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`. | [
"Helper",
"function",
"to",
"convert",
"the",
"SDP",
"problem",
"to",
"PICOS",
"and",
"call",
"CVXOPT",
"solver",
"and",
"parse",
"the",
"output",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/picos_utils.py#L13-L34 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/picos_utils.py | convert_to_picos | 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... | python | 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",
")",
":",
"import",
"picos",
"as",
"pic",
"import",
"cvxopt",
"as",
"cvx",
"P",
"=",
"pic",
".",
"Problem",
"(",
"verbose",
"=",
"sdp",
".",
"verbose",
")",
"block_size",
... | 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... | [
"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",
... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/picos_utils.py#L37-L125 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/cvxpy_utils.py | solve_with_cvxpy | 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... | python | 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",
")",
":",
"problem",
"=",
"convert_to_cvxpy",
"(",
"sdp",
")",
"if",
"solverparameters",
"is",
"not",
"None",
"and",
"'solver'",
"in",
"solverparameters",
":",
"solver",
"=",
"solverp... | 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`. | [
"Helper",
"function",
"to",
"convert",
"the",
"SDP",
"problem",
"to",
"CVXPY",
"and",
"call",
"the",
"solver",
"and",
"parse",
"the",
"output",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/cvxpy_utils.py#L14-L48 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/cvxpy_utils.py | convert_to_cvxpy | 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... | python | 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",
")",
":",
"from",
"cvxpy",
"import",
"Minimize",
",",
"Problem",
",",
"Variable",
"row_offsets",
"=",
"[",
"0",
"]",
"cumulative_sum",
"=",
"0",
"for",
"block_size",
"in",
"sdp",
".",
"block_struct",
":",
"cumulative_su... | Convert an SDP relaxation to a CVXPY problem.
:param sdp: The SDP relaxation to convert.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: :class:`cvxpy.Problem`. | [
"Convert",
"an",
"SDP",
"relaxation",
"to",
"a",
"CVXPY",
"problem",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/cvxpy_utils.py#L51-L94 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/physics_utils.py | get_neighbors | 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... | python | 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",
")",
":",
"if",
"width",
"==",
"0",
":",
"width",
"=",
"lattice_length",
"neighbors",
"=",
"[",
"]",
"coords",
"=",
"divmod",
"(",
"inde... | 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... | [
"Get",
"the",
"forward",
"neighbors",
"of",
"a",
"site",
"in",
"a",
"lattice",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L17-L44 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/physics_utils.py | get_next_neighbors | 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... | python | 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",
")",
":",
"if",
"not",
"isinstance",
"(",
"indices",
",",
"list",
")",
":",
"indices",
"=",
"[",
"indi... | 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.
... | [
"Get",
"the",
"forward",
"neighbors",
"at",
"a",
"given",
"distance",
"of",
"a",
"site",
"or",
"set",
"of",
"sites",
"in",
"a",
"lattice",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L47-L79 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/physics_utils.py | bosonic_constraints | 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):
... | python | 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",
")",
":",
"substitutions",
"=",
"{",
"}",
"for",
"i",
",",
"ai",
"in",
"enumerate",
"(",
"a",
")",
":",
"substitutions",
"[",
"ai",
"*",
"Dagger",
"(",
"ai",
")",
"]",
"=",
"1.0",
"+",
"Dagger",
"(",
"ai",
... | 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. | [
"Return",
"a",
"set",
"of",
"constraints",
"that",
"define",
"fermionic",
"ladder",
"operators",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L82-L99 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/physics_utils.py | fermionic_constraints | 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)... | python | 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",
")",
":",
"substitutions",
"=",
"{",
"}",
"for",
"i",
",",
"ai",
"in",
"enumerate",
"(",
"a",
")",
":",
"substitutions",
"[",
"ai",
"**",
"2",
"]",
"=",
"0",
"substitutions",
"[",
"Dagger",
"(",
"ai",
")",
... | 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. | [
"Return",
"a",
"set",
"of",
"constraints",
"that",
"define",
"fermionic",
"ladder",
"operators",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L102-L121 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/physics_utils.py | pauli_constraints | 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... | python | 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",
")",
":",
"substitutions",
"=",
"{",
"}",
"n_vars",
"=",
"len",
"(",
"X",
")",
"for",
"i",
"in",
"range",
"(",
"n_vars",
")",
":",
"# They square to the identity",
"substitutions",
"[",
"X",
"["... | 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`... | [
"Return",
"a",
"set",
"of",
"constraints",
"that",
"define",
"Pauli",
"spin",
"operators",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L124-L163 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/physics_utils.py | generate_measurements | 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... | python | 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",
")",
":",
"measurements",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"party",
")",
")",
":",
"measurements",
".",
"append",
"(",
"generate_operators",
"(",
"label",
"+",
"'%s'",
... | 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... | [
"Generate",
"variables",
"that",
"behave",
"like",
"measurements",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L166-L181 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/physics_utils.py | projective_measurement_constraints | 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... | python | 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",
")",
":",
"substitutions",
"=",
"{",
"}",
"# Idempotency and orthogonality of projectors",
"if",
"isinstance",
"(",
"parties",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"list",
")",
":",... | 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
... | [
"Return",
"a",
"set",
"of",
"constraints",
"that",
"define",
"projective",
"measurements",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L184-L216 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/physics_utils.py | define_objective_with_I | 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... | python | 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",
")",
":",
"objective",
"=",
"I",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"len",
"(",
"args",
")",
">",
"2",
"or",
"len",
"(",
"args",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"W... | 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 ... | [
"Define",
"a",
"polynomial",
"using",
"measurements",
"and",
"an",
"I",
"matrix",
"describing",
"a",
"Bell",
"inequality",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L219-L260 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/physics_utils.py | correlator | 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... | python | 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",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"A",
")",
")",
":",
"correlator_row",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"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.quantum.operator.HermitianOp... | [
"Correlators",
"between",
"the",
"probabilities",
"of",
"two",
"parties",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L263-L288 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/physics_utils.py | maximum_violation | 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... | python | 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",
")",
":",
"P",
"=",
"Probability",
"(",
"A_configuration",
",",
"B_configuration",
")",
"objective",
"=",
"define_objective_with_I",
"(... | 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... | [
"Get",
"the",
"maximum",
"violation",
"of",
"a",
"two",
"-",
"party",
"Bell",
"inequality",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L291-L316 | train |
bpython/curtsies | curtsies/formatstring.py | stable_format_dict | 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"')
... | python | 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",
")",
":",
"inner",
"=",
"', '",
".",
"join",
"(",
"'{}: {}'",
".",
"format",
"(",
"repr",
"(",
"k",
")",
"[",
"1",
":",
"]",
"if",
"repr",
"(",
"k",
")",
".",
"startswith",
"(",
"u\"u'\"",
")",
"or",
"repr",... | A sorted, python2/3 stable formatting of a dictionary.
Does not work for dicts with unicode strings as values. | [
"A",
"sorted",
"python2",
"/",
"3",
"stable",
"formatting",
"of",
"a",
"dictionary",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L67-L76 | train |
bpython/curtsies | curtsies/formatstring.py | interval_overlap | 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... | python | 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",
")",
":",
"if",
"b",
"<=",
"x",
"or",
"a",
">=",
"y",
":",
"return",
"0",
"elif",
"x",
"<=",
"a",
"<=",
"y",
":",
"return",
"min",
"(",
"b",
",",
"y",
")",
"-",
"a",
"elif... | Returns by how much two intervals overlap
assumed that a <= b and x <= y | [
"Returns",
"by",
"how",
"much",
"two",
"intervals",
"overlap"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L635-L648 | train |
bpython/curtsies | curtsies/formatstring.py | width_aware_slice | 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_... | python | 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)",
"divides",
"=",
"[",
"0",
"]",
"for",
"c",
"in",
"s",
":",
"divides",
".",
"append",
"(",
"divides",
"[",
"-... | >>> width_aware_slice(u'a\uff25iou', 0, 2)[1] == u' '
True | [
">>>",
"width_aware_slice",
"(",
"u",
"a",
"\\",
"uff25iou",
"0",
"2",
")",
"[",
"1",
"]",
"==",
"u",
"True"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L651-L671 | train |
bpython/curtsies | curtsies/formatstring.py | linesplit | 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
... | python | 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]",
"if",
"not",
"isinstance",
"(",
"string",
",",
"FmtStr",
")",
":",
"string",
"=",
"fmtstr",
"(",
"string",
")",
"string_s",
"=",
"string",
".",
"... | 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... | [
"Returns",
"a",
"list",
"of",
"lines",
"split",
"on",
"the",
"last",
"possible",
"space",
"of",
"each",
"line",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L674-L705 | train |
bpython/curtsies | curtsies/formatstring.py | normalize_slice | 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,... | python | 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",
")",
":",
"is_int",
"=",
"False",
"if",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"is_int",
"=",
"True",
"index",
"=",
"slice",
"(",
"index",
",",
"index",
"+",
"1",
")",
"if",
"index",
... | Fill in the Nones in a slice. | [
"Fill",
"in",
"the",
"Nones",
"in",
"a",
"slice",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L707-L726 | train |
bpython/curtsies | curtsies/formatstring.py | parse_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... | python | 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",
")",
":",
"if",
"'style'",
"in",
"kwargs",
":",
"args",
"+=",
"(",
"kwargs",
"[",
"'style'",
"]",
",",
")",
"del",
"kwargs",
"[",
"'style'",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"not",
"isinst... | Returns a kwargs dictionary by turning args into kwargs | [
"Returns",
"a",
"kwargs",
"dictionary",
"by",
"turning",
"args",
"into",
"kwargs"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L728-L759 | train |
bpython/curtsies | curtsies/formatstring.py | fmtstr | 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... | python | 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",
"atts",
"=",
"parse_args",
"(",
"args",
",",
"kwargs",
")",
"if",
"isinstance",
"(",
"string",
",",
"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"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L761-L778 | train |
bpython/curtsies | curtsies/formatstring.py | Chunk.color_str | 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... | python | 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",
")",
":",
"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... | Return an escape-coded string to write to the terminal. | [
"Return",
"an",
"escape",
"-",
"coded",
"string",
"to",
"write",
"to",
"the",
"terminal",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L106-L120 | train |
bpython/curtsies | curtsies/formatstring.py | Chunk.repr_part | 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 (... | python | 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",
")",
":",
"def",
"pp_att",
"(",
"att",
")",
":",
"if",
"att",
"==",
"'fg'",
":",
"return",
"FG_NUMBER_TO_COLOR",
"[",
"self",
".",
"atts",
"[",
"att",
"]",
"]",
"elif",
"att",
"==",
"'bg'",
":",
"return",
"'on_'",
"... | FmtStr repr is build by concatenating these. | [
"FmtStr",
"repr",
"is",
"build",
"by",
"concatenating",
"these",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L144-L152 | train |
bpython/curtsies | curtsies/formatstring.py | ChunkSplitter.request | 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)
... | python | 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]]",
"if",
"max_width",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'requires positive integer max_width'",
")",
"s",
"=",
"self",
".",
"chunk",
".",
"s",
"length... | Requests a sub-chunk of max_width or shorter. Returns None if no chunks left. | [
"Requests",
"a",
"sub",
"-",
"chunk",
"of",
"max_width",
"or",
"shorter",
".",
"Returns",
"None",
"if",
"no",
"chunks",
"left",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L180-L220 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.from_str | 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... | python | 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",
"if",
"'\\x1b['",
"in",
"s",
":",
"try",
":",
"tokens_and_strings",
"=",
"parse",
"(",
"s",
")",
"except",
"ValueError",
":",
"return",
"FmtStr",
"(",
"Chunk",
"(",
... | 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... | [
"r",
"Return",
"a",
"FmtStr",
"representing",
"input",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L239-L273 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.copy_with_new_str | 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... | python | 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",
")",
":",
"# What to do when there are multiple Chunks with conflicting atts?",
"old_atts",
"=",
"dict",
"(",
"(",
"att",
",",
"value",
")",
"for",
"bfs",
"in",
"self",
".",
"chunks",
"for",
"(",
"att",
",... | Copies the current FmtStr's attributes while changing its string. | [
"Copies",
"the",
"current",
"FmtStr",
"s",
"attributes",
"while",
"changing",
"its",
"string",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L275-L280 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.setitem | def setitem(self, startindex, fs):
"""Shim for easily converting old __setitem__ calls"""
return self.setslice_with_length(startindex, startindex+1, fs, len(self)) | python | 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",
")",
":",
"return",
"self",
".",
"setslice_with_length",
"(",
"startindex",
",",
"startindex",
"+",
"1",
",",
"fs",
",",
"len",
"(",
"self",
")",
")"
] | Shim for easily converting old __setitem__ calls | [
"Shim",
"for",
"easily",
"converting",
"old",
"__setitem__",
"calls"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L282-L284 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.setslice_with_length | 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))
... | python | 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",
")",
":",
"if",
"len",
"(",
"self",
")",
"<",
"startindex",
":",
"fs",
"=",
"' '",
"*",
"(",
"startindex",
"-",
"len",
"(",
"self",
")",
")",
... | Shim for easily converting old __setitem__ calls | [
"Shim",
"for",
"easily",
"converting",
"old",
"__setitem__",
"calls"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L286-L295 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.splice | 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... | python | 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",
")",
":",
"if",
"len",
"(",
"new_str",
")",
"==",
"0",
":",
"return",
"self",
"new_fs",
"=",
"new_str",
"if",
"isinstance",
"(",
"new_str",
",",
"FmtStr",
")",
"el... | 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]. | [
"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",
... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L297-L343 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.copy_with_new_atts | 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]) | python | 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",
")",
":",
"return",
"FmtStr",
"(",
"*",
"[",
"Chunk",
"(",
"bfs",
".",
"s",
",",
"bfs",
".",
"atts",
".",
"extend",
"(",
"attributes",
")",
")",
"for",
"bfs",
"in",
"self",
".",... | Returns a new FmtStr with the same content but new formatting | [
"Returns",
"a",
"new",
"FmtStr",
"with",
"the",
"same",
"content",
"but",
"new",
"formatting"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L348-L351 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.join | 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... | python | 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",
")",
":",
"before",
"=",
"[",
"]",
"chunks",
"=",
"[",
"]",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"iterable",
")",
":",
"chunks",
".",
"extend",
"(",
"before",
")",
"before",
"=",
"self",
".",
... | Joins an iterable yielding strings or FmtStrs with self as separator | [
"Joins",
"an",
"iterable",
"yielding",
"strings",
"or",
"FmtStrs",
"with",
"self",
"as",
"separator"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L353-L366 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.split | 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... | python | 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",
")",
":",
"if",
"maxsplit",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'no maxsplit yet'",
")",
"s",
"=",
"self",
".",
... | 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. | [
"Split",
"based",
"on",
"seperator",
"optionally",
"using",
"a",
"regex"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L369-L384 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.splitlines | 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]) | python | 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",
")",
":",
"lines",
"=",
"self",
".",
"split",
"(",
"'\\n'",
")",
"return",
"[",
"line",
"+",
"'\\n'",
"for",
"line",
"in",
"lines",
"]",
"if",
"keepends",
"else",
"(",
"lines",
"if",
... | Return a list of lines, split on newline characters,
include line boundaries, if keepends is true. | [
"Return",
"a",
"list",
"of",
"lines",
"split",
"on",
"newline",
"characters",
"include",
"line",
"boundaries",
"if",
"keepends",
"is",
"true",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L386-L391 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.ljust | 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... | python | 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",
")",
":",
"if",
"fillchar",
"is",
"not",
"None",
":",
"return",
"fmtstr",
"(",
"self",
".",
"s",
".",
"ljust",
"(",
"width",
",",
"fillchar",
")",
",",
"*",
"*",
"self",
"."... | S.ljust(width[, fillchar]) -> string
If a fillchar is provided, less formatting information will be preserved | [
"S",
".",
"ljust",
"(",
"width",
"[",
"fillchar",
"]",
")",
"-",
">",
"string"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L395-L408 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.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 | python | 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",
")",
":",
"if",
"self",
".",
"_width",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_width",
"self",
".",
"_width",
"=",
"sum",
"(",
"fs",
".",
"width",
"for",
"fs",
"in",
"self",
".",
"chunks",
")",
"return",
"s... | The number of columns it would take to display this string | [
"The",
"number",
"of",
"columns",
"it",
"would",
"take",
"to",
"display",
"this",
"string"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L447-L452 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.width_at_offset | 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 | python | 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",
")",
":",
"#TODO make more efficient?",
"width",
"=",
"wcswidth",
"(",
"self",
".",
"s",
"[",
":",
"n",
"]",
")",
"assert",
"width",
"!=",
"-",
"1",
"return",
"width"
] | Returns the horizontal position of character n of the string | [
"Returns",
"the",
"horizontal",
"position",
"of",
"character",
"n",
"of",
"the",
"string"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L454-L459 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.shared_atts | 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... | python | 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",
")",
":",
"#TODO cache this, could get ugly for large FmtStrs",
"atts",
"=",
"{",
"}",
"first",
"=",
"self",
".",
"chunks",
"[",
"0",
"]",
"for",
"att",
"in",
"sorted",
"(",
"first",
".",
"atts",
")",
":",
"#TODO how to wri... | Gets atts shared among all nonzero length component Chunk | [
"Gets",
"atts",
"shared",
"among",
"all",
"nonzero",
"length",
"component",
"Chunk"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L494-L503 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.new_with_atts_removed | 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]) | python | 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",
")",
":",
"return",
"FmtStr",
"(",
"*",
"[",
"Chunk",
"(",
"bfs",
".",
"s",
",",
"bfs",
".",
"atts",
".",
"remove",
"(",
"*",
"attributes",
")",
")",
"for",
"bfs",
"in",
"self",
"... | Returns a new FmtStr with the same content but some attributes removed | [
"Returns",
"a",
"new",
"FmtStr",
"with",
"the",
"same",
"content",
"but",
"some",
"attributes",
"removed"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L505-L508 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.divides | 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 | python | 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",
")",
":",
"acc",
"=",
"[",
"0",
"]",
"for",
"s",
"in",
"self",
".",
"chunks",
":",
"acc",
".",
"append",
"(",
"acc",
"[",
"-",
"1",
"]",
"+",
"len",
"(",
"s",
")",
")",
"return",
"acc"
] | List of indices of divisions between the constituent chunks. | [
"List",
"of",
"indices",
"of",
"divisions",
"between",
"the",
"constituent",
"chunks",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L525-L530 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.width_aware_slice | 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 = []
... | python | 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",
")",
":",
"if",
"wcswidth",
"(",
"self",
".",
"s",
")",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'bad values for width aware slicing'",
")",
"index",
"=",
"normalize_slice",
"(",
"self",
".",
... | Slice based on the number of columns it would take to display the substring. | [
"Slice",
"based",
"on",
"the",
"number",
"of",
"columns",
"it",
"would",
"take",
"to",
"display",
"the",
"substring",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L557-L576 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr.width_aware_splitlines | 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 ... | python | 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]",
"if",
"columns",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"Column width %s is too narrow.\"",
"%",
"columns",
")",
"if",
"wcswidth",
"(",
"self",
".",
... | 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. | [
"Split",
"into",
"lines",
"pushing",
"doublewidth",
"characters",
"at",
"the",
"end",
"of",
"a",
"line",
"to",
"the",
"next",
"line",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L578-L588 | train |
bpython/curtsies | curtsies/formatstring.py | FmtStr._getitem_normalized | 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... | python | 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",
")",
":",
"index",
"=",
"normalize_slice",
"(",
"len",
"(",
"self",
")",
",",
"index",
")",
"counter",
"=",
"0",
"output",
"=",
"''",
"for",
"fs",
"in",
"self",
".",
"chunks",
":",
"if",
"index... | Builds the more compact fmtstrs by using fromstr( of the control sequences) | [
"Builds",
"the",
"more",
"compact",
"fmtstrs",
"by",
"using",
"fromstr",
"(",
"of",
"the",
"control",
"sequences",
")"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L613-L626 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/moroder_hierarchy.py | MoroderHierarchy._calculate_block_structure | def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_struct=None):
"""Calculates the block_struct array for the outp... | python | 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",
")",
":",
"block_struct",
"=",
"[",
"]"... | Calculates the block_struct array for the output file. | [
"Calculates",
"the",
"block_struct",
"array",
"for",
"the",
"output",
"file",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/moroder_hierarchy.py#L81-L101 | train |
bpython/curtsies | examples/initial_input.py | main | 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)) | python | 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",
"(",
")",
":",
"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 | [
"Ideally",
"we",
"shouldn",
"t",
"lose",
"the",
"first",
"second",
"of",
"events"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/initial_input.py#L5-L10 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/steering_hierarchy.py | SteeringHierarchy._process_monomial | 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... | python | 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",
")",
":",
"coeff",
",",
"monomial",
"=",
"monomial",
".",
"as_coeff_Mul",
"(",
")",
"k",
"=",
"0",
"# Have we seen this monomial before?",
"conjugate",
"=",
"False",
"try",
":",
"# If yes... | Process a single monomial when building the moment matrix. | [
"Process",
"a",
"single",
"monomial",
"when",
"building",
"the",
"moment",
"matrix",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L80-L108 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/steering_hierarchy.py | SteeringHierarchy.__get_trace_facvar | 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... | python | 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",
")",
":",
"facvar",
"=",
"[",
"0",
"]",
"*",
"(",
"self",
".",
"n_vars",
"+",
"1",
")",
"F",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"matrix_var_dim",
")",
":",
"for... | 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. | [
"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... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/steering_hierarchy.py#L186-L219 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.