id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
242,900 | stitchfix/pyxley | pyxley/charts/datatables/datatable.py | DataTable.format_row | def format_row(row, bounds, columns):
"""Formats a single row of the dataframe"""
for c in columns:
if c not in row:
continue
if "format" in columns[c]:
row[c] = columns[c]["format"] % row[c]
if c in bounds:
b = bounds... | python | def format_row(row, bounds, columns):
for c in columns:
if c not in row:
continue
if "format" in columns[c]:
row[c] = columns[c]["format"] % row[c]
if c in bounds:
b = bounds[c]
row[c] = [b["min"],row[b["lower"... | [
"def",
"format_row",
"(",
"row",
",",
"bounds",
",",
"columns",
")",
":",
"for",
"c",
"in",
"columns",
":",
"if",
"c",
"not",
"in",
"row",
":",
"continue",
"if",
"\"format\"",
"in",
"columns",
"[",
"c",
"]",
":",
"row",
"[",
"c",
"]",
"=",
"colum... | Formats a single row of the dataframe | [
"Formats",
"a",
"single",
"row",
"of",
"the",
"dataframe"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/datatables/datatable.py#L70-L83 |
242,901 | stitchfix/pyxley | pyxley/charts/datatables/datatable.py | DataTable.to_json | def to_json(df, columns, confidence={}):
"""Transforms dataframe to properly formatted json response"""
records = []
display_cols = list(columns.keys())
if not display_cols:
display_cols = list(df.columns)
bounds = {}
for c in confidence:
bounds[... | python | def to_json(df, columns, confidence={}):
records = []
display_cols = list(columns.keys())
if not display_cols:
display_cols = list(df.columns)
bounds = {}
for c in confidence:
bounds[c] = {
"min": df[confidence[c]["lower"]].min(),
... | [
"def",
"to_json",
"(",
"df",
",",
"columns",
",",
"confidence",
"=",
"{",
"}",
")",
":",
"records",
"=",
"[",
"]",
"display_cols",
"=",
"list",
"(",
"columns",
".",
"keys",
"(",
")",
")",
"if",
"not",
"display_cols",
":",
"display_cols",
"=",
"list",... | Transforms dataframe to properly formatted json response | [
"Transforms",
"dataframe",
"to",
"properly",
"formatted",
"json",
"response"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/datatables/datatable.py#L86-L117 |
242,902 | stitchfix/pyxley | pyxley/charts/mg/figure.py | Figure.get | def get(self):
"""Return axes, graphics, and layout options."""
options = {}
for x in [self.axes, self.graphics, self.layout]:
for k, v in list(x.get().items()):
options[k] = v
return options | python | def get(self):
options = {}
for x in [self.axes, self.graphics, self.layout]:
for k, v in list(x.get().items()):
options[k] = v
return options | [
"def",
"get",
"(",
"self",
")",
":",
"options",
"=",
"{",
"}",
"for",
"x",
"in",
"[",
"self",
".",
"axes",
",",
"self",
".",
"graphics",
",",
"self",
".",
"layout",
"]",
":",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"x",
".",
"get",
"(",
")... | Return axes, graphics, and layout options. | [
"Return",
"axes",
"graphics",
"and",
"layout",
"options",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/figure.py#L22-L29 |
242,903 | stitchfix/pyxley | pyxley/charts/mg/layout.py | Layout.set_margin | def set_margin(self, top=40, bottom=30, left=50, right=10, buffer_size=8):
"""Set margin of the chart.
Args:
top (int): size of top margin in pixels.
bottom (int): size of bottom margin in pixels.
left (int): size of left margin in pixels.
... | python | def set_margin(self, top=40, bottom=30, left=50, right=10, buffer_size=8):
self.set_integer("top", top)
self.set_integer("bottom", bottom)
self.set_integer("left", left)
self.set_integer("right", right)
self.set_integer("buffer", buffer_size) | [
"def",
"set_margin",
"(",
"self",
",",
"top",
"=",
"40",
",",
"bottom",
"=",
"30",
",",
"left",
"=",
"50",
",",
"right",
"=",
"10",
",",
"buffer_size",
"=",
"8",
")",
":",
"self",
".",
"set_integer",
"(",
"\"top\"",
",",
"top",
")",
"self",
".",
... | Set margin of the chart.
Args:
top (int): size of top margin in pixels.
bottom (int): size of bottom margin in pixels.
left (int): size of left margin in pixels.
right (int): size of right margin in pixels.
buffer_size (int): b... | [
"Set",
"margin",
"of",
"the",
"chart",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/layout.py#L20-L35 |
242,904 | stitchfix/pyxley | pyxley/charts/mg/layout.py | Layout.set_size | def set_size(self, height=220, width=350,
height_threshold=120,
width_threshold=160):
"""Set the size of the chart.
Args:
height (int): height in pixels.
width (int): width in pixels.
height_threshold (int): height th... | python | def set_size(self, height=220, width=350,
height_threshold=120,
width_threshold=160):
self.set_integer("height", height)
self.set_integer("width", width)
self.set_integer("small_height_threshold", height_threshold)
self.set_integer("small_width_threshold... | [
"def",
"set_size",
"(",
"self",
",",
"height",
"=",
"220",
",",
"width",
"=",
"350",
",",
"height_threshold",
"=",
"120",
",",
"width_threshold",
"=",
"160",
")",
":",
"self",
".",
"set_integer",
"(",
"\"height\"",
",",
"height",
")",
"self",
".",
"set... | Set the size of the chart.
Args:
height (int): height in pixels.
width (int): width in pixels.
height_threshold (int): height threshold in pixels
width_threshold (int): width threshold in pixesls | [
"Set",
"the",
"size",
"of",
"the",
"chart",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/layout.py#L37-L52 |
242,905 | stitchfix/pyxley | pyxley/charts/mg/layout.py | Layout.get | def get(self):
"""Get layout options."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_layout} | python | def get(self):
return {k:v for k,v in list(self.options.items()) if k in self._allowed_layout} | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"self",
".",
"options",
".",
"items",
"(",
")",
")",
"if",
"k",
"in",
"self",
".",
"_allowed_layout",
"}"
] | Get layout options. | [
"Get",
"layout",
"options",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/layout.py#L54-L56 |
242,906 | stitchfix/pyxley | pyxley/react_template.py | format_props | def format_props(props, prop_template="{{k}} = { {{v}} }", delim="\n"):
""" Formats props for the React template.
Args:
props (dict): properties to be written to the template.
Returns:
Two lists, one containing variable names and the other
containing a list of p... | python | def format_props(props, prop_template="{{k}} = { {{v}} }", delim="\n"):
vars_ = []
props_ = []
for k, v in list(props.items()):
vars_.append(Template("var {{k}} = {{v}};").render(k=k,v=json.dumps(v)))
props_.append(Template(prop_template).render(k=k, v=k))
return "\n".join(vars_), delim.... | [
"def",
"format_props",
"(",
"props",
",",
"prop_template",
"=",
"\"{{k}} = { {{v}} }\"",
",",
"delim",
"=",
"\"\\n\"",
")",
":",
"vars_",
"=",
"[",
"]",
"props_",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"props",
".",
"items",
"(",
")"... | Formats props for the React template.
Args:
props (dict): properties to be written to the template.
Returns:
Two lists, one containing variable names and the other
containing a list of props to be fed to the React template. | [
"Formats",
"props",
"for",
"the",
"React",
"template",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/react_template.py#L35-L51 |
242,907 | stitchfix/pyxley | pyxley/ui.py | register_layouts | def register_layouts(layouts, app, url="/api/props/", brand="Pyxley"):
""" register UILayout with the flask app
create a function that will send props for each UILayout
Args:
layouts (dict): dict of UILayout objects by name
app (object): flask app
url (string): ... | python | def register_layouts(layouts, app, url="/api/props/", brand="Pyxley"):
def props(name):
if name not in layouts:
# cast as list for python3
name = list(layouts.keys())[0]
return jsonify({"layouts": layouts[name]["layout"]})
def apps():
paths = []
for i, k ... | [
"def",
"register_layouts",
"(",
"layouts",
",",
"app",
",",
"url",
"=",
"\"/api/props/\"",
",",
"brand",
"=",
"\"Pyxley\"",
")",
":",
"def",
"props",
"(",
"name",
")",
":",
"if",
"name",
"not",
"in",
"layouts",
":",
"# cast as list for python3",
"name",
"=... | register UILayout with the flask app
create a function that will send props for each UILayout
Args:
layouts (dict): dict of UILayout objects by name
app (object): flask app
url (string): address of props; default is /api/props/ | [
"register",
"UILayout",
"with",
"the",
"flask",
"app"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L5-L38 |
242,908 | stitchfix/pyxley | pyxley/ui.py | UIComponent.register_route | def register_route(self, app):
"""Register the api route function with the app."""
if "url" not in self.params["options"]:
raise Exception("Component does not have a URL property")
if not hasattr(self.route_func, "__call__"):
raise Exception("No app route function suppli... | python | def register_route(self, app):
if "url" not in self.params["options"]:
raise Exception("Component does not have a URL property")
if not hasattr(self.route_func, "__call__"):
raise Exception("No app route function supplied")
app.add_url_rule(self.params["options"]["url"]... | [
"def",
"register_route",
"(",
"self",
",",
"app",
")",
":",
"if",
"\"url\"",
"not",
"in",
"self",
".",
"params",
"[",
"\"options\"",
"]",
":",
"raise",
"Exception",
"(",
"\"Component does not have a URL property\"",
")",
"if",
"not",
"hasattr",
"(",
"self",
... | Register the api route function with the app. | [
"Register",
"the",
"api",
"route",
"function",
"with",
"the",
"app",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L61-L71 |
242,909 | stitchfix/pyxley | pyxley/ui.py | SimpleComponent.render | def render(self, path):
"""Render the component to a javascript file."""
return ReactComponent(
self.layout,
self.src_file,
self.component_id,
props=self.props,
static_path=path) | python | def render(self, path):
return ReactComponent(
self.layout,
self.src_file,
self.component_id,
props=self.props,
static_path=path) | [
"def",
"render",
"(",
"self",
",",
"path",
")",
":",
"return",
"ReactComponent",
"(",
"self",
".",
"layout",
",",
"self",
".",
"src_file",
",",
"self",
".",
"component_id",
",",
"props",
"=",
"self",
".",
"props",
",",
"static_path",
"=",
"path",
")"
] | Render the component to a javascript file. | [
"Render",
"the",
"component",
"to",
"a",
"javascript",
"file",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L93-L100 |
242,910 | stitchfix/pyxley | pyxley/ui.py | UILayout.add_filter | def add_filter(self, component, filter_group="pyxley-filter"):
"""Add a filter to the layout."""
if getattr(component, "name") != "Filter":
raise Exception("Component is not an instance of Filter")
if filter_group not in self.filters:
self.filters[filter_group] = []
... | python | def add_filter(self, component, filter_group="pyxley-filter"):
if getattr(component, "name") != "Filter":
raise Exception("Component is not an instance of Filter")
if filter_group not in self.filters:
self.filters[filter_group] = []
self.filters[filter_group].append(compo... | [
"def",
"add_filter",
"(",
"self",
",",
"component",
",",
"filter_group",
"=",
"\"pyxley-filter\"",
")",
":",
"if",
"getattr",
"(",
"component",
",",
"\"name\"",
")",
"!=",
"\"Filter\"",
":",
"raise",
"Exception",
"(",
"\"Component is not an instance of Filter\"",
... | Add a filter to the layout. | [
"Add",
"a",
"filter",
"to",
"the",
"layout",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L128-L134 |
242,911 | stitchfix/pyxley | pyxley/ui.py | UILayout.add_chart | def add_chart(self, component):
"""Add a chart to the layout."""
if getattr(component, "name") != "Chart":
raise Exception("Component is not an instance of Chart")
self.charts.append(component) | python | def add_chart(self, component):
if getattr(component, "name") != "Chart":
raise Exception("Component is not an instance of Chart")
self.charts.append(component) | [
"def",
"add_chart",
"(",
"self",
",",
"component",
")",
":",
"if",
"getattr",
"(",
"component",
",",
"\"name\"",
")",
"!=",
"\"Chart\"",
":",
"raise",
"Exception",
"(",
"\"Component is not an instance of Chart\"",
")",
"self",
".",
"charts",
".",
"append",
"("... | Add a chart to the layout. | [
"Add",
"a",
"chart",
"to",
"the",
"layout",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L136-L140 |
242,912 | stitchfix/pyxley | pyxley/ui.py | UILayout.build_props | def build_props(self):
"""Build the props dictionary."""
props = {}
if self.filters:
props["filters"] = {}
for grp in self.filters:
props["filters"][grp] = [f.params for f in self.filters[grp]]
if self.charts:
props["charts"] = [c.param... | python | def build_props(self):
props = {}
if self.filters:
props["filters"] = {}
for grp in self.filters:
props["filters"][grp] = [f.params for f in self.filters[grp]]
if self.charts:
props["charts"] = [c.params for c in self.charts]
props["ty... | [
"def",
"build_props",
"(",
"self",
")",
":",
"props",
"=",
"{",
"}",
"if",
"self",
".",
"filters",
":",
"props",
"[",
"\"filters\"",
"]",
"=",
"{",
"}",
"for",
"grp",
"in",
"self",
".",
"filters",
":",
"props",
"[",
"\"filters\"",
"]",
"[",
"grp",
... | Build the props dictionary. | [
"Build",
"the",
"props",
"dictionary",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L142-L153 |
242,913 | stitchfix/pyxley | pyxley/ui.py | UILayout.assign_routes | def assign_routes(self, app):
"""Register routes with the app."""
for grp in self.filters:
for f in self.filters[grp]:
if f.route_func:
f.register_route(app)
for c in self.charts:
if c.route_func:
c.register_route(app) | python | def assign_routes(self, app):
for grp in self.filters:
for f in self.filters[grp]:
if f.route_func:
f.register_route(app)
for c in self.charts:
if c.route_func:
c.register_route(app) | [
"def",
"assign_routes",
"(",
"self",
",",
"app",
")",
":",
"for",
"grp",
"in",
"self",
".",
"filters",
":",
"for",
"f",
"in",
"self",
".",
"filters",
"[",
"grp",
"]",
":",
"if",
"f",
".",
"route_func",
":",
"f",
".",
"register_route",
"(",
"app",
... | Register routes with the app. | [
"Register",
"routes",
"with",
"the",
"app",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L155-L164 |
242,914 | stitchfix/pyxley | pyxley/ui.py | UILayout.render_layout | def render_layout(self, app, path, alias=None):
"""Write to javascript."""
self.assign_routes(app)
return ReactComponent(
self.layout,
self.src_file,
self.component_id,
props=self.build_props(),
static_path=path,
alias=alias... | python | def render_layout(self, app, path, alias=None):
self.assign_routes(app)
return ReactComponent(
self.layout,
self.src_file,
self.component_id,
props=self.build_props(),
static_path=path,
alias=alias) | [
"def",
"render_layout",
"(",
"self",
",",
"app",
",",
"path",
",",
"alias",
"=",
"None",
")",
":",
"self",
".",
"assign_routes",
"(",
"app",
")",
"return",
"ReactComponent",
"(",
"self",
".",
"layout",
",",
"self",
".",
"src_file",
",",
"self",
".",
... | Write to javascript. | [
"Write",
"to",
"javascript",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/ui.py#L166-L175 |
242,915 | stitchfix/pyxley | pyxley/utils/flask_helper.py | default_static_path | def default_static_path():
"""
Return the path to the javascript bundle
"""
fdir = os.path.dirname(__file__)
return os.path.abspath(os.path.join(fdir, '../assets/')) | python | def default_static_path():
fdir = os.path.dirname(__file__)
return os.path.abspath(os.path.join(fdir, '../assets/')) | [
"def",
"default_static_path",
"(",
")",
":",
"fdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"fdir",
",",
"'../assets/'",
")",
")"
] | Return the path to the javascript bundle | [
"Return",
"the",
"path",
"to",
"the",
"javascript",
"bundle"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/utils/flask_helper.py#L31-L36 |
242,916 | stitchfix/pyxley | pyxley/utils/flask_helper.py | default_template_path | def default_template_path():
"""
Return the path to the index.html
"""
fdir = os.path.dirname(__file__)
return os.path.abspath(os.path.join(fdir, '../assets/')) | python | def default_template_path():
fdir = os.path.dirname(__file__)
return os.path.abspath(os.path.join(fdir, '../assets/')) | [
"def",
"default_template_path",
"(",
")",
":",
"fdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"fdir",
",",
"'../assets/'",
")",
")"
] | Return the path to the index.html | [
"Return",
"the",
"path",
"to",
"the",
"index",
".",
"html"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/utils/flask_helper.py#L38-L43 |
242,917 | stitchfix/pyxley | pyxley/charts/mg/axes.py | Axes.set_xlim | def set_xlim(self, xlim):
""" Set x-axis limits.
Accepts a two-element list to set the x-axis limits.
Args:
xlim (list): lower and upper bounds
Raises:
ValueError: xlim must contain two elements
ValueError: Min must be less t... | python | def set_xlim(self, xlim):
if len(xlim) != 2:
raise ValueError("xlim must contain two elements")
if xlim[1] < xlim[0]:
raise ValueError("Min must be less than Max")
self.options["min_x"] = xlim[0]
self.options["max_x"] = xlim[1] | [
"def",
"set_xlim",
"(",
"self",
",",
"xlim",
")",
":",
"if",
"len",
"(",
"xlim",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"xlim must contain two elements\"",
")",
"if",
"xlim",
"[",
"1",
"]",
"<",
"xlim",
"[",
"0",
"]",
":",
"raise",
"Value... | Set x-axis limits.
Accepts a two-element list to set the x-axis limits.
Args:
xlim (list): lower and upper bounds
Raises:
ValueError: xlim must contain two elements
ValueError: Min must be less than max | [
"Set",
"x",
"-",
"axis",
"limits",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/axes.py#L46-L65 |
242,918 | stitchfix/pyxley | pyxley/charts/mg/axes.py | Axes.set_ylim | def set_ylim(self, ylim):
""" Set y-axis limits.
Accepts a two-element list to set the y-axis limits.
Args:
ylim (list): lower and upper bounds
Raises:
ValueError: ylim must contain two elements
ValueError: Min must be less t... | python | def set_ylim(self, ylim):
if len(ylim) != 2:
raise ValueError("ylim must contain two elements")
if ylim[1] < ylim[0]:
raise ValueError("Min must be less than Max")
self.options["min_y"] = ylim[0]
self.options["max_y"] = ylim[1] | [
"def",
"set_ylim",
"(",
"self",
",",
"ylim",
")",
":",
"if",
"len",
"(",
"ylim",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"ylim must contain two elements\"",
")",
"if",
"ylim",
"[",
"1",
"]",
"<",
"ylim",
"[",
"0",
"]",
":",
"raise",
"Value... | Set y-axis limits.
Accepts a two-element list to set the y-axis limits.
Args:
ylim (list): lower and upper bounds
Raises:
ValueError: ylim must contain two elements
ValueError: Min must be less than max | [
"Set",
"y",
"-",
"axis",
"limits",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/axes.py#L67-L86 |
242,919 | stitchfix/pyxley | pyxley/charts/mg/axes.py | Axes.get | def get(self):
""" Retrieve options set by user."""
return {k:v for k,v in list(self.options.items()) if k in self._allowed_axes} | python | def get(self):
return {k:v for k,v in list(self.options.items()) if k in self._allowed_axes} | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"self",
".",
"options",
".",
"items",
"(",
")",
")",
"if",
"k",
"in",
"self",
".",
"_allowed_axes",
"}"
] | Retrieve options set by user. | [
"Retrieve",
"options",
"set",
"by",
"user",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/axes.py#L168-L170 |
242,920 | stitchfix/pyxley | pyxley/charts/plotly/base.py | PlotlyAPI.line_plot | def line_plot(df, xypairs, mode, layout={}, config=_BASE_CONFIG):
""" basic line plot
dataframe to json for a line plot
Args:
df (pandas.DataFrame): input dataframe
xypairs (list): list of tuples containing column names
mode (str): plotly... | python | def line_plot(df, xypairs, mode, layout={}, config=_BASE_CONFIG):
if df.empty:
return {
"x": [],
"y": [],
"mode": mode
}
_data = []
for x, y in xypairs:
if (x in df.columns) and (y in df.columns):
... | [
"def",
"line_plot",
"(",
"df",
",",
"xypairs",
",",
"mode",
",",
"layout",
"=",
"{",
"}",
",",
"config",
"=",
"_BASE_CONFIG",
")",
":",
"if",
"df",
".",
"empty",
":",
"return",
"{",
"\"x\"",
":",
"[",
"]",
",",
"\"y\"",
":",
"[",
"]",
",",
"\"m... | basic line plot
dataframe to json for a line plot
Args:
df (pandas.DataFrame): input dataframe
xypairs (list): list of tuples containing column names
mode (str): plotly.js mode (e.g. lines)
layout (dict): layout parameters
... | [
"basic",
"line",
"plot"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/plotly/base.py#L32-L66 |
242,921 | stitchfix/pyxley | pyxley/charts/nvd3/pie_chart.py | PieChart.to_json | def to_json(df, values):
"""Format output for the json response."""
records = []
if df.empty:
return {"data": []}
sum_ = float(np.sum([df[c].iloc[0] for c in values]))
for c in values:
records.append({
"label": values[c],
"... | python | def to_json(df, values):
records = []
if df.empty:
return {"data": []}
sum_ = float(np.sum([df[c].iloc[0] for c in values]))
for c in values:
records.append({
"label": values[c],
"value": "%.2f"%np.around(df[c].iloc[0] / sum_, deci... | [
"def",
"to_json",
"(",
"df",
",",
"values",
")",
":",
"records",
"=",
"[",
"]",
"if",
"df",
".",
"empty",
":",
"return",
"{",
"\"data\"",
":",
"[",
"]",
"}",
"sum_",
"=",
"float",
"(",
"np",
".",
"sum",
"(",
"[",
"df",
"[",
"c",
"]",
".",
"... | Format output for the json response. | [
"Format",
"output",
"for",
"the",
"json",
"response",
"."
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/nvd3/pie_chart.py#L57-L71 |
242,922 | stitchfix/pyxley | pyxley/charts/datamaps/datamaps.py | DatamapUSA.to_json | def to_json(df, state_index, color_index, fills):
"""Transforms dataframe to json response"""
records = {}
for i, row in df.iterrows():
records[row[state_index]] = {
"fillKey": row[color_index]
}
return {
"data": records,
... | python | def to_json(df, state_index, color_index, fills):
records = {}
for i, row in df.iterrows():
records[row[state_index]] = {
"fillKey": row[color_index]
}
return {
"data": records,
"fills": fills
} | [
"def",
"to_json",
"(",
"df",
",",
"state_index",
",",
"color_index",
",",
"fills",
")",
":",
"records",
"=",
"{",
"}",
"for",
"i",
",",
"row",
"in",
"df",
".",
"iterrows",
"(",
")",
":",
"records",
"[",
"row",
"[",
"state_index",
"]",
"]",
"=",
"... | Transforms dataframe to json response | [
"Transforms",
"dataframe",
"to",
"json",
"response"
] | 2dab00022d977d986169cd8a629b3a2f91be893f | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/datamaps/datamaps.py#L123-L135 |
242,923 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | error_string | def error_string(mqtt_errno):
"""Return the error string associated with an mqtt error number."""
if mqtt_errno == MQTT_ERR_SUCCESS:
return "No error."
elif mqtt_errno == MQTT_ERR_NOMEM:
return "Out of memory."
elif mqtt_errno == MQTT_ERR_PROTOCOL:
return "A network protocol erro... | python | def error_string(mqtt_errno):
if mqtt_errno == MQTT_ERR_SUCCESS:
return "No error."
elif mqtt_errno == MQTT_ERR_NOMEM:
return "Out of memory."
elif mqtt_errno == MQTT_ERR_PROTOCOL:
return "A network protocol error occurred when communicating with the broker."
elif mqtt_errno == M... | [
"def",
"error_string",
"(",
"mqtt_errno",
")",
":",
"if",
"mqtt_errno",
"==",
"MQTT_ERR_SUCCESS",
":",
"return",
"\"No error.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_NOMEM",
":",
"return",
"\"Out of memory.\"",
"elif",
"mqtt_errno",
"==",
"MQTT_ERR_PROTOCOL",
":",
... | Return the error string associated with an mqtt error number. | [
"Return",
"the",
"error",
"string",
"associated",
"with",
"an",
"mqtt",
"error",
"number",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L145-L178 |
242,924 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | topic_matches_sub | def topic_matches_sub(sub, topic):
"""Check whether a topic matches a subscription.
For example:
foo/bar would match the subscription foo/# or +/bar
non/matching would not match the subscription non/+/+
"""
result = True
multilevel_wildcard = False
slen = len(sub)
tlen = len(topic... | python | def topic_matches_sub(sub, topic):
result = True
multilevel_wildcard = False
slen = len(sub)
tlen = len(topic)
if slen > 0 and tlen > 0:
if (sub[0] == '$' and topic[0] != '$') or (topic[0] == '$' and sub[0] != '$'):
return False
spos = 0
tpos = 0
while spos < slen... | [
"def",
"topic_matches_sub",
"(",
"sub",
",",
"topic",
")",
":",
"result",
"=",
"True",
"multilevel_wildcard",
"=",
"False",
"slen",
"=",
"len",
"(",
"sub",
")",
"tlen",
"=",
"len",
"(",
"topic",
")",
"if",
"slen",
">",
"0",
"and",
"tlen",
">",
"0",
... | Check whether a topic matches a subscription.
For example:
foo/bar would match the subscription foo/# or +/bar
non/matching would not match the subscription non/+/+ | [
"Check",
"whether",
"a",
"topic",
"matches",
"a",
"subscription",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L199-L261 |
242,925 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.configIAMCredentials | def configIAMCredentials(self, srcAWSAccessKeyID, srcAWSSecretAccessKey, srcAWSSessionToken):
"""
Make custom settings for IAM credentials for websocket connection
srcAWSAccessKeyID - AWS IAM access key
srcAWSSecretAccessKey - AWS IAM secret key
srcAWSSessionToken - AWS Session T... | python | def configIAMCredentials(self, srcAWSAccessKeyID, srcAWSSecretAccessKey, srcAWSSessionToken):
self._AWSAccessKeyIDCustomConfig = srcAWSAccessKeyID
self._AWSSecretAccessKeyCustomConfig = srcAWSSecretAccessKey
self._AWSSessionTokenCustomConfig = srcAWSSessionToken | [
"def",
"configIAMCredentials",
"(",
"self",
",",
"srcAWSAccessKeyID",
",",
"srcAWSSecretAccessKey",
",",
"srcAWSSessionToken",
")",
":",
"self",
".",
"_AWSAccessKeyIDCustomConfig",
"=",
"srcAWSAccessKeyID",
"self",
".",
"_AWSSecretAccessKeyCustomConfig",
"=",
"srcAWSSecretA... | Make custom settings for IAM credentials for websocket connection
srcAWSAccessKeyID - AWS IAM access key
srcAWSSecretAccessKey - AWS IAM secret key
srcAWSSessionToken - AWS Session Token | [
"Make",
"custom",
"settings",
"for",
"IAM",
"credentials",
"for",
"websocket",
"connection",
"srcAWSAccessKeyID",
"-",
"AWS",
"IAM",
"access",
"key",
"srcAWSSecretAccessKey",
"-",
"AWS",
"IAM",
"secret",
"key",
"srcAWSSessionToken",
"-",
"AWS",
"Session",
"Token"
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L526-L535 |
242,926 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.loop | def loop(self, timeout=1.0, max_packets=1):
"""Process network events.
This function must be called regularly to ensure communication with the
broker is carried out. It calls select() on the network socket to wait
for network events. If incoming data is present it will then be
p... | python | def loop(self, timeout=1.0, max_packets=1):
if timeout < 0.0:
raise ValueError('Invalid timeout.')
self._current_out_packet_mutex.acquire()
self._out_packet_mutex.acquire()
if self._current_out_packet is None and len(self._out_packet) > 0:
self._current_out_packe... | [
"def",
"loop",
"(",
"self",
",",
"timeout",
"=",
"1.0",
",",
"max_packets",
"=",
"1",
")",
":",
"if",
"timeout",
"<",
"0.0",
":",
"raise",
"ValueError",
"(",
"'Invalid timeout.'",
")",
"self",
".",
"_current_out_packet_mutex",
".",
"acquire",
"(",
")",
"... | Process network events.
This function must be called regularly to ensure communication with the
broker is carried out. It calls select() on the network socket to wait
for network events. If incoming data is present it will then be
processed. Outgoing commands, from e.g. publish(), are n... | [
"Process",
"network",
"events",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L842-L913 |
242,927 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.publish | def publish(self, topic, payload=None, qos=0, retain=False):
"""Publish a message on a topic.
This causes a message to be sent to the broker and subsequently from
the broker to any clients subscribing to matching topics.
topic: The topic that the message should be published on.
... | python | def publish(self, topic, payload=None, qos=0, retain=False):
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if isinstance(payload, str) or isinstance(payload, bytearray):
local_... | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"payload",
"=",
"None",
",",
"qos",
"=",
"0",
",",
"retain",
"=",
"False",
")",
":",
"if",
"topic",
"is",
"None",
"or",
"len",
"(",
"topic",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Inva... | Publish a message on a topic.
This causes a message to be sent to the broker and subsequently from
the broker to any clients subscribing to matching topics.
topic: The topic that the message should be published on.
payload: The actual message to send. If not given, or set to None a
... | [
"Publish",
"a",
"message",
"on",
"a",
"topic",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L915-L1003 |
242,928 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.username_pw_set | def username_pw_set(self, username, password=None):
"""Set a username and optionally a password for broker authentication.
Must be called before connect() to have any effect.
Requires a broker that supports MQTT v3.1.
username: The username to authenticate with. Need have no relationsh... | python | def username_pw_set(self, username, password=None):
self._username = username.encode('utf-8')
self._password = password | [
"def",
"username_pw_set",
"(",
"self",
",",
"username",
",",
"password",
"=",
"None",
")",
":",
"self",
".",
"_username",
"=",
"username",
".",
"encode",
"(",
"'utf-8'",
")",
"self",
".",
"_password",
"=",
"password"
] | Set a username and optionally a password for broker authentication.
Must be called before connect() to have any effect.
Requires a broker that supports MQTT v3.1.
username: The username to authenticate with. Need have no relationship to the client id.
password: The password to authenti... | [
"Set",
"a",
"username",
"and",
"optionally",
"a",
"password",
"for",
"broker",
"authentication",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1005-L1015 |
242,929 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.disconnect | def disconnect(self):
"""Disconnect a connected client from the broker."""
self._state_mutex.acquire()
self._state = mqtt_cs_disconnecting
self._state_mutex.release()
self._backoffCore.stopStableConnectionTimer()
if self._sock is None and self._ssl is None:
... | python | def disconnect(self):
self._state_mutex.acquire()
self._state = mqtt_cs_disconnecting
self._state_mutex.release()
self._backoffCore.stopStableConnectionTimer()
if self._sock is None and self._ssl is None:
return MQTT_ERR_NO_CONN
return self._send_disconnect... | [
"def",
"disconnect",
"(",
"self",
")",
":",
"self",
".",
"_state_mutex",
".",
"acquire",
"(",
")",
"self",
".",
"_state",
"=",
"mqtt_cs_disconnecting",
"self",
".",
"_state_mutex",
".",
"release",
"(",
")",
"self",
".",
"_backoffCore",
".",
"stopStableConnec... | Disconnect a connected client from the broker. | [
"Disconnect",
"a",
"connected",
"client",
"from",
"the",
"broker",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1017-L1028 |
242,930 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.subscribe | def subscribe(self, topic, qos=0):
"""Subscribe the client to one or more topics.
This function may be called in three different ways:
Simple string and integer
-------------------------
e.g. subscribe("my/topic", 2)
topic: A string specifying the subscription topic to... | python | def subscribe(self, topic, qos=0):
topic_qos_list = None
if isinstance(topic, str):
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
topic_qos_list = [(top... | [
"def",
"subscribe",
"(",
"self",
",",
"topic",
",",
"qos",
"=",
"0",
")",
":",
"topic_qos_list",
"=",
"None",
"if",
"isinstance",
"(",
"topic",
",",
"str",
")",
":",
"if",
"qos",
"<",
"0",
"or",
"qos",
">",
"2",
":",
"raise",
"ValueError",
"(",
"... | Subscribe the client to one or more topics.
This function may be called in three different ways:
Simple string and integer
-------------------------
e.g. subscribe("my/topic", 2)
topic: A string specifying the subscription topic to subscribe to.
qos: The desired qualit... | [
"Subscribe",
"the",
"client",
"to",
"one",
"or",
"more",
"topics",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1030-L1101 |
242,931 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.unsubscribe | def unsubscribe(self, topic):
"""Unsubscribe the client from one or more topics.
topic: A single string, or list of strings that are the subscription
topics to unsubscribe from.
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS
to indicate success or (MQTT_... | python | def unsubscribe(self, topic):
topic_list = None
if topic is None:
raise ValueError('Invalid topic.')
if isinstance(topic, str):
if len(topic) == 0:
raise ValueError('Invalid topic.')
topic_list = [topic.encode('utf-8')]
elif isinstance(... | [
"def",
"unsubscribe",
"(",
"self",
",",
"topic",
")",
":",
"topic_list",
"=",
"None",
"if",
"topic",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Invalid topic.'",
")",
"if",
"isinstance",
"(",
"topic",
",",
"str",
")",
":",
"if",
"len",
"(",
"topi... | Unsubscribe the client from one or more topics.
topic: A single string, or list of strings that are the subscription
topics to unsubscribe from.
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS
to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not
... | [
"Unsubscribe",
"the",
"client",
"from",
"one",
"or",
"more",
"topics",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1103-L1139 |
242,932 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.will_set | def will_set(self, topic, payload=None, qos=0, retain=False):
"""Set a Will to be sent by the broker in case the client disconnects unexpectedly.
This must be called before connect() to have any effect.
topic: The topic that the will message should be published on.
payload: The message... | python | def will_set(self, topic, payload=None, qos=0, retain=False):
if topic is None or len(topic) == 0:
raise ValueError('Invalid topic.')
if qos<0 or qos>2:
raise ValueError('Invalid QoS level.')
if isinstance(payload, str):
self._will_payload = payload.encode('ut... | [
"def",
"will_set",
"(",
"self",
",",
"topic",
",",
"payload",
"=",
"None",
",",
"qos",
"=",
"0",
",",
"retain",
"=",
"False",
")",
":",
"if",
"topic",
"is",
"None",
"or",
"len",
"(",
"topic",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Inv... | Set a Will to be sent by the broker in case the client disconnects unexpectedly.
This must be called before connect() to have any effect.
topic: The topic that the will message should be published on.
payload: The message to send as a will. If not given, or set to None a
zero length me... | [
"Set",
"a",
"Will",
"to",
"be",
"sent",
"by",
"the",
"broker",
"in",
"case",
"the",
"client",
"disconnects",
"unexpectedly",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1257-L1293 |
242,933 | aws/aws-iot-device-sdk-python | AWSIoTPythonSDK/core/protocol/paho/client.py | Client.socket | def socket(self):
"""Return the socket or ssl object for this client."""
if self._ssl:
if self._useSecuredWebsocket:
return self._ssl.getSSLSocket()
else:
return self._ssl
else:
return self._sock | python | def socket(self):
if self._ssl:
if self._useSecuredWebsocket:
return self._ssl.getSSLSocket()
else:
return self._ssl
else:
return self._sock | [
"def",
"socket",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ssl",
":",
"if",
"self",
".",
"_useSecuredWebsocket",
":",
"return",
"self",
".",
"_ssl",
".",
"getSSLSocket",
"(",
")",
"else",
":",
"return",
"self",
".",
"_ssl",
"else",
":",
"return",
"... | Return the socket or ssl object for this client. | [
"Return",
"the",
"socket",
"or",
"ssl",
"object",
"for",
"this",
"client",
"."
] | f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62 | https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1305-L1313 |
242,934 | mcneel/rhino3dm | src/build_python_project.py | createproject | def createproject():
""" compile for the platform we are running on """
os.chdir(build_dir)
if windows_build:
command = 'cmake -A {} -DPYTHON_EXECUTABLE:FILEPATH="{}" ../..'.format("win32" if bitness==32 else "x64", sys.executable)
os.system(command)
if bitness==64:
for l... | python | def createproject():
os.chdir(build_dir)
if windows_build:
command = 'cmake -A {} -DPYTHON_EXECUTABLE:FILEPATH="{}" ../..'.format("win32" if bitness==32 else "x64", sys.executable)
os.system(command)
if bitness==64:
for line in fileinput.input("_rhino3dm.vcxproj", inplace=1):... | [
"def",
"createproject",
"(",
")",
":",
"os",
".",
"chdir",
"(",
"build_dir",
")",
"if",
"windows_build",
":",
"command",
"=",
"'cmake -A {} -DPYTHON_EXECUTABLE:FILEPATH=\"{}\" ../..'",
".",
"format",
"(",
"\"win32\"",
"if",
"bitness",
"==",
"32",
"else",
"\"x64\""... | compile for the platform we are running on | [
"compile",
"for",
"the",
"platform",
"we",
"are",
"running",
"on"
] | 89e4e46c9a07c4243ea51572de7897e03a4acda2 | https://github.com/mcneel/rhino3dm/blob/89e4e46c9a07c4243ea51572de7897e03a4acda2/src/build_python_project.py#L24-L38 |
242,935 | getsentry/responses | responses.py | RequestsMock.add_passthru | def add_passthru(self, prefix):
"""
Register a URL prefix to passthru any non-matching mock requests to.
For example, to allow any request to 'https://example.com', but require
mocks for the remainder, you would add the prefix as so:
>>> responses.add_passthru('https://example.... | python | def add_passthru(self, prefix):
if _has_unicode(prefix):
prefix = _clean_unicode(prefix)
self.passthru_prefixes += (prefix,) | [
"def",
"add_passthru",
"(",
"self",
",",
"prefix",
")",
":",
"if",
"_has_unicode",
"(",
"prefix",
")",
":",
"prefix",
"=",
"_clean_unicode",
"(",
"prefix",
")",
"self",
".",
"passthru_prefixes",
"+=",
"(",
"prefix",
",",
")"
] | Register a URL prefix to passthru any non-matching mock requests to.
For example, to allow any request to 'https://example.com', but require
mocks for the remainder, you would add the prefix as so:
>>> responses.add_passthru('https://example.com') | [
"Register",
"a",
"URL",
"prefix",
"to",
"passthru",
"any",
"non",
"-",
"matching",
"mock",
"requests",
"to",
"."
] | b7ab59513ffd52bf28808f45005f492f7d1bbd50 | https://github.com/getsentry/responses/blob/b7ab59513ffd52bf28808f45005f492f7d1bbd50/responses.py#L489-L500 |
242,936 | martinblech/xmltodict | ez_setup.py | _install | def _install(archive_filename, install_args=()):
"""Install Setuptools."""
with archive_context(archive_filename):
# installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.'... | python | def _install(archive_filename, install_args=()):
with archive_context(archive_filename):
# installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See th... | [
"def",
"_install",
"(",
"archive_filename",
",",
"install_args",
"=",
"(",
")",
")",
":",
"with",
"archive_context",
"(",
"archive_filename",
")",
":",
"# installing",
"log",
".",
"warn",
"(",
"'Installing Setuptools'",
")",
"if",
"not",
"_python_cmd",
"(",
"'... | Install Setuptools. | [
"Install",
"Setuptools",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L57-L66 |
242,937 | martinblech/xmltodict | ez_setup.py | _build_egg | def _build_egg(egg, archive_filename, to_dir):
"""Build Setuptools egg."""
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
# returning the result
log.war... | python | def _build_egg(egg, archive_filename, to_dir):
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
# returning the result
log.warn(egg)
if not os.path.exists... | [
"def",
"_build_egg",
"(",
"egg",
",",
"archive_filename",
",",
"to_dir",
")",
":",
"with",
"archive_context",
"(",
"archive_filename",
")",
":",
"# building an egg",
"log",
".",
"warn",
"(",
"'Building a Setuptools egg in %s'",
",",
"to_dir",
")",
"_python_cmd",
"... | Build Setuptools egg. | [
"Build",
"Setuptools",
"egg",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L69-L78 |
242,938 | martinblech/xmltodict | ez_setup.py | _do_download | def _do_download(version, download_base, to_dir, download_delay):
"""Download Setuptools."""
py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)
tp = 'setuptools-{version}-{py_desig}.egg'
egg = os.path.join(to_dir, tp.format(**locals()))
if not os.path.exists(egg):
arc... | python | def _do_download(version, download_base, to_dir, download_delay):
py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)
tp = 'setuptools-{version}-{py_desig}.egg'
egg = os.path.join(to_dir, tp.format(**locals()))
if not os.path.exists(egg):
archive = download_setuptools(vers... | [
"def",
"_do_download",
"(",
"version",
",",
"download_base",
",",
"to_dir",
",",
"download_delay",
")",
":",
"py_desig",
"=",
"'py{sys.version_info[0]}.{sys.version_info[1]}'",
".",
"format",
"(",
"sys",
"=",
"sys",
")",
"tp",
"=",
"'setuptools-{version}-{py_desig}.eg... | Download Setuptools. | [
"Download",
"Setuptools",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L132-L149 |
242,939 | martinblech/xmltodict | ez_setup.py | use_setuptools | def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=DEFAULT_SAVE_DIR, download_delay=15):
"""
Ensure that a setuptools version is installed.
Return None. Raise SystemExit if the requested version
or later cannot be installed.
"""
to_dir = os.path.abspa... | python | def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=DEFAULT_SAVE_DIR, download_delay=15):
to_dir = os.path.abspath(to_dir)
# prior to importing, capture the module state for
# representative modules.
rep_modules = 'pkg_resources', 'setuptools'
imported = s... | [
"def",
"use_setuptools",
"(",
"version",
"=",
"DEFAULT_VERSION",
",",
"download_base",
"=",
"DEFAULT_URL",
",",
"to_dir",
"=",
"DEFAULT_SAVE_DIR",
",",
"download_delay",
"=",
"15",
")",
":",
"to_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"to_dir",
")... | Ensure that a setuptools version is installed.
Return None. Raise SystemExit if the requested version
or later cannot be installed. | [
"Ensure",
"that",
"a",
"setuptools",
"version",
"is",
"installed",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L152-L188 |
242,940 | martinblech/xmltodict | ez_setup.py | _conflict_bail | def _conflict_bail(VC_err, version):
"""
Setuptools was imported prior to invocation, so it is
unsafe to unload it. Bail out.
"""
conflict_tmpl = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running... | python | def _conflict_bail(VC_err, version):
conflict_tmpl = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.
(C... | [
"def",
"_conflict_bail",
"(",
"VC_err",
",",
"version",
")",
":",
"conflict_tmpl",
"=",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\n The required version of setuptools (>={version}) is not available,\n and can't be installed while this script is running. Please\n instal... | Setuptools was imported prior to invocation, so it is
unsafe to unload it. Bail out. | [
"Setuptools",
"was",
"imported",
"prior",
"to",
"invocation",
"so",
"it",
"is",
"unsafe",
"to",
"unload",
"it",
".",
"Bail",
"out",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L191-L206 |
242,941 | martinblech/xmltodict | ez_setup.py | download_file_insecure | def download_file_insecure(url, target):
"""Use Python to download the file, without connection authentication."""
src = urlopen(url)
try:
# Read all the data in one block.
data = src.read()
finally:
src.close()
# Write all the data in one block to avoid creating a partial f... | python | def download_file_insecure(url, target):
src = urlopen(url)
try:
# Read all the data in one block.
data = src.read()
finally:
src.close()
# Write all the data in one block to avoid creating a partial file.
with open(target, "wb") as dst:
dst.write(data) | [
"def",
"download_file_insecure",
"(",
"url",
",",
"target",
")",
":",
"src",
"=",
"urlopen",
"(",
"url",
")",
"try",
":",
"# Read all the data in one block.",
"data",
"=",
"src",
".",
"read",
"(",
")",
"finally",
":",
"src",
".",
"close",
"(",
")",
"# Wr... | Use Python to download the file, without connection authentication. | [
"Use",
"Python",
"to",
"download",
"the",
"file",
"without",
"connection",
"authentication",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L305-L316 |
242,942 | martinblech/xmltodict | ez_setup.py | _download_args | def _download_args(options):
"""Return args for download_setuptools function from cmdline args."""
return dict(
version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory,
to_dir=options.to_dir,
) | python | def _download_args(options):
return dict(
version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory,
to_dir=options.to_dir,
) | [
"def",
"_download_args",
"(",
"options",
")",
":",
"return",
"dict",
"(",
"version",
"=",
"options",
".",
"version",
",",
"download_base",
"=",
"options",
".",
"download_base",
",",
"downloader_factory",
"=",
"options",
".",
"downloader_factory",
",",
"to_dir",
... | Return args for download_setuptools function from cmdline args. | [
"Return",
"args",
"for",
"download_setuptools",
"function",
"from",
"cmdline",
"args",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L397-L404 |
242,943 | martinblech/xmltodict | ez_setup.py | main | def main():
"""Install or upgrade setuptools and EasyInstall."""
options = _parse_args()
archive = download_setuptools(**_download_args(options))
return _install(archive, _build_install_args(options)) | python | def main():
options = _parse_args()
archive = download_setuptools(**_download_args(options))
return _install(archive, _build_install_args(options)) | [
"def",
"main",
"(",
")",
":",
"options",
"=",
"_parse_args",
"(",
")",
"archive",
"=",
"download_setuptools",
"(",
"*",
"*",
"_download_args",
"(",
"options",
")",
")",
"return",
"_install",
"(",
"archive",
",",
"_build_install_args",
"(",
"options",
")",
... | Install or upgrade setuptools and EasyInstall. | [
"Install",
"or",
"upgrade",
"setuptools",
"and",
"EasyInstall",
"."
] | f3ab7e1740d37d585ffab0154edb4cb664afe4a9 | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L407-L411 |
242,944 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.registerContract | def registerContract(self, contract):
""" used for when callback receives a contract
that isn't found in local database """
if contract.m_exchange == "":
return
"""
if contract not in self.contracts.values():
contract_tuple = self.contract_to_tuple(contr... | python | def registerContract(self, contract):
if contract.m_exchange == "":
return
"""
if contract not in self.contracts.values():
contract_tuple = self.contract_to_tuple(contract)
self.createContract(contract_tuple)
if self.tickerId(contract) not in self.co... | [
"def",
"registerContract",
"(",
"self",
",",
"contract",
")",
":",
"if",
"contract",
".",
"m_exchange",
"==",
"\"\"",
":",
"return",
"\"\"\"\n if contract not in self.contracts.values():\n contract_tuple = self.contract_to_tuple(contract)\n self.createCon... | used for when callback receives a contract
that isn't found in local database | [
"used",
"for",
"when",
"callback",
"receives",
"a",
"contract",
"that",
"isn",
"t",
"found",
"in",
"local",
"database"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L245-L264 |
242,945 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handleErrorEvents | def handleErrorEvents(self, msg):
""" logs error messages """
# https://www.interactivebrokers.com/en/software/api/apiguide/tables/api_message_codes.htm
if msg.errorCode is not None and msg.errorCode != -1 and \
msg.errorCode not in dataTypes["BENIGN_ERROR_CODES"]:
l... | python | def handleErrorEvents(self, msg):
# https://www.interactivebrokers.com/en/software/api/apiguide/tables/api_message_codes.htm
if msg.errorCode is not None and msg.errorCode != -1 and \
msg.errorCode not in dataTypes["BENIGN_ERROR_CODES"]:
log = True
# log disconn... | [
"def",
"handleErrorEvents",
"(",
"self",
",",
"msg",
")",
":",
"# https://www.interactivebrokers.com/en/software/api/apiguide/tables/api_message_codes.htm",
"if",
"msg",
".",
"errorCode",
"is",
"not",
"None",
"and",
"msg",
".",
"errorCode",
"!=",
"-",
"1",
"and",
"msg... | logs error messages | [
"logs",
"error",
"messages"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L269-L286 |
242,946 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handleServerEvents | def handleServerEvents(self, msg):
""" dispatch msg to the right handler """
self.log.debug('MSG %s', msg)
self.handleConnectionState(msg)
if msg.typeName == "error":
self.handleErrorEvents(msg)
elif msg.typeName == dataTypes["MSG_CURRENT_TIME"]:
if sel... | python | def handleServerEvents(self, msg):
self.log.debug('MSG %s', msg)
self.handleConnectionState(msg)
if msg.typeName == "error":
self.handleErrorEvents(msg)
elif msg.typeName == dataTypes["MSG_CURRENT_TIME"]:
if self.time < msg.time:
self.time = msg.... | [
"def",
"handleServerEvents",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'MSG %s'",
",",
"msg",
")",
"self",
".",
"handleConnectionState",
"(",
"msg",
")",
"if",
"msg",
".",
"typeName",
"==",
"\"error\"",
":",
"self",
"."... | dispatch msg to the right handler | [
"dispatch",
"msg",
"to",
"the",
"right",
"handler"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L289-L361 |
242,947 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handleContractDetails | def handleContractDetails(self, msg, end=False):
""" handles contractDetails and contractDetailsEnd """
if end:
# mark as downloaded
self._contract_details[msg.reqId]['downloaded'] = True
# move details from temp to permanent collector
self.contract_deta... | python | def handleContractDetails(self, msg, end=False):
if end:
# mark as downloaded
self._contract_details[msg.reqId]['downloaded'] = True
# move details from temp to permanent collector
self.contract_details[msg.reqId] = self._contract_details[msg.reqId]
d... | [
"def",
"handleContractDetails",
"(",
"self",
",",
"msg",
",",
"end",
"=",
"False",
")",
":",
"if",
"end",
":",
"# mark as downloaded",
"self",
".",
"_contract_details",
"[",
"msg",
".",
"reqId",
"]",
"[",
"'downloaded'",
"]",
"=",
"True",
"# move details fro... | handles contractDetails and contractDetailsEnd | [
"handles",
"contractDetails",
"and",
"contractDetailsEnd"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L411-L487 |
242,948 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handlePosition | def handlePosition(self, msg):
""" handle positions changes """
# log handler msg
self.log_msg("position", msg)
# contract identifier
contract_tuple = self.contract_to_tuple(msg.contract)
contractString = self.contractString(contract_tuple)
# try creating the c... | python | def handlePosition(self, msg):
# log handler msg
self.log_msg("position", msg)
# contract identifier
contract_tuple = self.contract_to_tuple(msg.contract)
contractString = self.contractString(contract_tuple)
# try creating the contract
self.registerContract(msg.... | [
"def",
"handlePosition",
"(",
"self",
",",
"msg",
")",
":",
"# log handler msg",
"self",
".",
"log_msg",
"(",
"\"position\"",
",",
"msg",
")",
"# contract identifier",
"contract_tuple",
"=",
"self",
".",
"contract_to_tuple",
"(",
"msg",
".",
"contract",
")",
"... | handle positions changes | [
"handle",
"positions",
"changes"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L553-L579 |
242,949 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handlePortfolio | def handlePortfolio(self, msg):
""" handle portfolio updates """
# log handler msg
self.log_msg("portfolio", msg)
# contract identifier
contract_tuple = self.contract_to_tuple(msg.contract)
contractString = self.contractString(contract_tuple)
# try creating the... | python | def handlePortfolio(self, msg):
# log handler msg
self.log_msg("portfolio", msg)
# contract identifier
contract_tuple = self.contract_to_tuple(msg.contract)
contractString = self.contractString(contract_tuple)
# try creating the contract
self.registerContract(ms... | [
"def",
"handlePortfolio",
"(",
"self",
",",
"msg",
")",
":",
"# log handler msg",
"self",
".",
"log_msg",
"(",
"\"portfolio\"",
",",
"msg",
")",
"# contract identifier",
"contract_tuple",
"=",
"self",
".",
"contract_to_tuple",
"(",
"msg",
".",
"contract",
")",
... | handle portfolio updates | [
"handle",
"portfolio",
"updates"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L600-L630 |
242,950 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handleOrders | def handleOrders(self, msg):
""" handle order open & status """
"""
It is possible that orderStatus() may return duplicate messages.
It is essential that you filter the message accordingly.
"""
# log handler msg
self.log_msg("order", msg)
# get server ti... | python | def handleOrders(self, msg):
"""
It is possible that orderStatus() may return duplicate messages.
It is essential that you filter the message accordingly.
"""
# log handler msg
self.log_msg("order", msg)
# get server time
self.getServerTime()
tim... | [
"def",
"handleOrders",
"(",
"self",
",",
"msg",
")",
":",
"\"\"\"\n It is possible that orderStatus() may return duplicate messages.\n It is essential that you filter the message accordingly.\n \"\"\"",
"# log handler msg",
"self",
".",
"log_msg",
"(",
"\"order\"",
... | handle order open & status | [
"handle",
"order",
"open",
"&",
"status"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L655-L727 |
242,951 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createTriggerableTrailingStop | def createTriggerableTrailingStop(self, symbol, quantity=1,
triggerPrice=0, trailPercent=100., trailAmount=0.,
parentId=0, stopOrderId=None, **kwargs):
""" adds order to triggerable list """
ticksize = self.contractDetails(symbol)["m_minTick"]
self.triggerableTrailingSt... | python | def createTriggerableTrailingStop(self, symbol, quantity=1,
triggerPrice=0, trailPercent=100., trailAmount=0.,
parentId=0, stopOrderId=None, **kwargs):
ticksize = self.contractDetails(symbol)["m_minTick"]
self.triggerableTrailingStops[symbol] = {
"parentId": parentId... | [
"def",
"createTriggerableTrailingStop",
"(",
"self",
",",
"symbol",
",",
"quantity",
"=",
"1",
",",
"triggerPrice",
"=",
"0",
",",
"trailPercent",
"=",
"100.",
",",
"trailAmount",
"=",
"0.",
",",
"parentId",
"=",
"0",
",",
"stopOrderId",
"=",
"None",
",",
... | adds order to triggerable list | [
"adds",
"order",
"to",
"triggerable",
"list"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1101-L1118 |
242,952 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.registerTrailingStop | def registerTrailingStop(self, tickerId, orderId=0, quantity=1,
lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs):
""" adds trailing stop to monitor list """
ticksize = self.contractDetails(tickerId)["m_minTick"]
trailingStop = self.trailingStops[tickerId] = {
... | python | def registerTrailingStop(self, tickerId, orderId=0, quantity=1,
lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs):
ticksize = self.contractDetails(tickerId)["m_minTick"]
trailingStop = self.trailingStops[tickerId] = {
"orderId": orderId,
"parentId... | [
"def",
"registerTrailingStop",
"(",
"self",
",",
"tickerId",
",",
"orderId",
"=",
"0",
",",
"quantity",
"=",
"1",
",",
"lastPrice",
"=",
"0",
",",
"trailPercent",
"=",
"100.",
",",
"trailAmount",
"=",
"0.",
",",
"parentId",
"=",
"0",
",",
"*",
"*",
"... | adds trailing stop to monitor list | [
"adds",
"trailing",
"stop",
"to",
"monitor",
"list"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1121-L1137 |
242,953 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.modifyStopOrder | def modifyStopOrder(self, orderId, parentId, newStop, quantity,
transmit=True, account=None):
""" modify stop order """
if orderId in self.orders.keys():
order = self.createStopOrder(
quantity = quantity,
parentId = parentId,
... | python | def modifyStopOrder(self, orderId, parentId, newStop, quantity,
transmit=True, account=None):
if orderId in self.orders.keys():
order = self.createStopOrder(
quantity = quantity,
parentId = parentId,
stop = newStop,
... | [
"def",
"modifyStopOrder",
"(",
"self",
",",
"orderId",
",",
"parentId",
",",
"newStop",
",",
"quantity",
",",
"transmit",
"=",
"True",
",",
"account",
"=",
"None",
")",
":",
"if",
"orderId",
"in",
"self",
".",
"orders",
".",
"keys",
"(",
")",
":",
"o... | modify stop order | [
"modify",
"stop",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1140-L1154 |
242,954 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.handleTrailingStops | def handleTrailingStops(self, tickerId):
""" software-based trailing stop """
# existing?
if tickerId not in self.trailingStops.keys():
return None
# continue
trailingStop = self.trailingStops[tickerId]
price = self.marketData[tickerId]['last'][0]... | python | def handleTrailingStops(self, tickerId):
# existing?
if tickerId not in self.trailingStops.keys():
return None
# continue
trailingStop = self.trailingStops[tickerId]
price = self.marketData[tickerId]['last'][0]
symbol = self.tickerSymbol(ti... | [
"def",
"handleTrailingStops",
"(",
"self",
",",
"tickerId",
")",
":",
"# existing?",
"if",
"tickerId",
"not",
"in",
"self",
".",
"trailingStops",
".",
"keys",
"(",
")",
":",
"return",
"None",
"# continue",
"trailingStop",
"=",
"self",
".",
"trailingStops",
"... | software-based trailing stop | [
"software",
"-",
"based",
"trailing",
"stop"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1157-L1214 |
242,955 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.triggerTrailingStops | def triggerTrailingStops(self, tickerId):
""" trigger waiting trailing stops """
# print('.')
# test
symbol = self.tickerSymbol(tickerId)
price = self.marketData[tickerId]['last'][0]
# contract = self.contracts[tickerId]
if symbol in self.triggerableTrailingStop... | python | def triggerTrailingStops(self, tickerId):
# print('.')
# test
symbol = self.tickerSymbol(tickerId)
price = self.marketData[tickerId]['last'][0]
# contract = self.contracts[tickerId]
if symbol in self.triggerableTrailingStops.keys():
pendingOrder = self.trigg... | [
"def",
"triggerTrailingStops",
"(",
"self",
",",
"tickerId",
")",
":",
"# print('.')",
"# test",
"symbol",
"=",
"self",
".",
"tickerSymbol",
"(",
"tickerId",
")",
"price",
"=",
"self",
".",
"marketData",
"[",
"tickerId",
"]",
"[",
"'last'",
"]",
"[",
"0",
... | trigger waiting trailing stops | [
"trigger",
"waiting",
"trailing",
"stops"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1217-L1299 |
242,956 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.tickerId | def tickerId(self, contract_identifier):
"""
returns the tickerId for the symbol or
sets one if it doesn't exits
"""
# contract passed instead of symbol?
symbol = contract_identifier
if isinstance(symbol, Contract):
symbol = self.contractString(symbol)... | python | def tickerId(self, contract_identifier):
# contract passed instead of symbol?
symbol = contract_identifier
if isinstance(symbol, Contract):
symbol = self.contractString(symbol)
for tickerId in self.tickerIds:
if symbol == self.tickerIds[tickerId]:
... | [
"def",
"tickerId",
"(",
"self",
",",
"contract_identifier",
")",
":",
"# contract passed instead of symbol?",
"symbol",
"=",
"contract_identifier",
"if",
"isinstance",
"(",
"symbol",
",",
"Contract",
")",
":",
"symbol",
"=",
"self",
".",
"contractString",
"(",
"sy... | returns the tickerId for the symbol or
sets one if it doesn't exits | [
"returns",
"the",
"tickerId",
"for",
"the",
"symbol",
"or",
"sets",
"one",
"if",
"it",
"doesn",
"t",
"exits"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1304-L1320 |
242,957 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createTargetOrder | def createTargetOrder(self, quantity, parentId=0,
target=0., orderType=None, transmit=True, group=None, tif="DAY",
rth=False, account=None):
""" Creates TARGET order """
order = self.createOrder(quantity,
price = target,
transmit = tra... | python | def createTargetOrder(self, quantity, parentId=0,
target=0., orderType=None, transmit=True, group=None, tif="DAY",
rth=False, account=None):
order = self.createOrder(quantity,
price = target,
transmit = transmit,
orderType ... | [
"def",
"createTargetOrder",
"(",
"self",
",",
"quantity",
",",
"parentId",
"=",
"0",
",",
"target",
"=",
"0.",
",",
"orderType",
"=",
"None",
",",
"transmit",
"=",
"True",
",",
"group",
"=",
"None",
",",
"tif",
"=",
"\"DAY\"",
",",
"rth",
"=",
"False... | Creates TARGET order | [
"Creates",
"TARGET",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1598-L1612 |
242,958 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createStopOrder | def createStopOrder(self, quantity, parentId=0, stop=0., trail=None,
transmit=True, group=None, stop_limit=False, rth=False, tif="DAY",
account=None):
""" Creates STOP order """
if trail:
if trail == "percent":
order = self.createOrder(quantity,
... | python | def createStopOrder(self, quantity, parentId=0, stop=0., trail=None,
transmit=True, group=None, stop_limit=False, rth=False, tif="DAY",
account=None):
if trail:
if trail == "percent":
order = self.createOrder(quantity,
trailingPerc... | [
"def",
"createStopOrder",
"(",
"self",
",",
"quantity",
",",
"parentId",
"=",
"0",
",",
"stop",
"=",
"0.",
",",
"trail",
"=",
"None",
",",
"transmit",
"=",
"True",
",",
"group",
"=",
"None",
",",
"stop_limit",
"=",
"False",
",",
"rth",
"=",
"False",
... | Creates STOP order | [
"Creates",
"STOP",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1615-L1657 |
242,959 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createTrailingStopOrder | def createTrailingStopOrder(self, contract, quantity,
parentId=0, trailPercent=100., group=None, triggerPrice=None,
account=None):
""" convert hard stop order to trailing stop order """
if parentId not in self.orders:
raise ValueError("Order #" + str(parentId) + " do... | python | def createTrailingStopOrder(self, contract, quantity,
parentId=0, trailPercent=100., group=None, triggerPrice=None,
account=None):
if parentId not in self.orders:
raise ValueError("Order #" + str(parentId) + " doesn't exist or wasn't submitted")
order = self.createS... | [
"def",
"createTrailingStopOrder",
"(",
"self",
",",
"contract",
",",
"quantity",
",",
"parentId",
"=",
"0",
",",
"trailPercent",
"=",
"100.",
",",
"group",
"=",
"None",
",",
"triggerPrice",
"=",
"None",
",",
"account",
"=",
"None",
")",
":",
"if",
"paren... | convert hard stop order to trailing stop order | [
"convert",
"hard",
"stop",
"order",
"to",
"trailing",
"stop",
"order"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1660-L1678 |
242,960 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.placeOrder | def placeOrder(self, contract, order, orderId=None, account=None):
""" Place order on IB TWS """
# get latest order id before submitting an order
self.requestOrderIds()
# continue...
useOrderId = self.orderId if orderId == None else orderId
if account:
order... | python | def placeOrder(self, contract, order, orderId=None, account=None):
# get latest order id before submitting an order
self.requestOrderIds()
# continue...
useOrderId = self.orderId if orderId == None else orderId
if account:
order.m_account = account
self.ibCon... | [
"def",
"placeOrder",
"(",
"self",
",",
"contract",
",",
"order",
",",
"orderId",
"=",
"None",
",",
"account",
"=",
"None",
")",
":",
"# get latest order id before submitting an order",
"self",
".",
"requestOrderIds",
"(",
")",
"# continue...",
"useOrderId",
"=",
... | Place order on IB TWS | [
"Place",
"order",
"on",
"IB",
"TWS"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1750-L1778 |
242,961 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.cancelOrder | def cancelOrder(self, orderId):
""" cancel order on IB TWS """
self.ibConn.cancelOrder(orderId)
# update order id for next time
self.requestOrderIds()
return orderId | python | def cancelOrder(self, orderId):
self.ibConn.cancelOrder(orderId)
# update order id for next time
self.requestOrderIds()
return orderId | [
"def",
"cancelOrder",
"(",
"self",
",",
"orderId",
")",
":",
"self",
".",
"ibConn",
".",
"cancelOrder",
"(",
"orderId",
")",
"# update order id for next time",
"self",
".",
"requestOrderIds",
"(",
")",
"return",
"orderId"
] | cancel order on IB TWS | [
"cancel",
"order",
"on",
"IB",
"TWS"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1781-L1787 |
242,962 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.requestOpenOrders | def requestOpenOrders(self, all_clients=False):
"""
Request open orders - loads up orders that wasn't created using this session
"""
if all_clients:
self.ibConn.reqAllOpenOrders()
self.ibConn.reqOpenOrders() | python | def requestOpenOrders(self, all_clients=False):
if all_clients:
self.ibConn.reqAllOpenOrders()
self.ibConn.reqOpenOrders() | [
"def",
"requestOpenOrders",
"(",
"self",
",",
"all_clients",
"=",
"False",
")",
":",
"if",
"all_clients",
":",
"self",
".",
"ibConn",
".",
"reqAllOpenOrders",
"(",
")",
"self",
".",
"ibConn",
".",
"reqOpenOrders",
"(",
")"
] | Request open orders - loads up orders that wasn't created using this session | [
"Request",
"open",
"orders",
"-",
"loads",
"up",
"orders",
"that",
"wasn",
"t",
"created",
"using",
"this",
"session"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1793-L1799 |
242,963 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.cancelHistoricalData | def cancelHistoricalData(self, contracts=None):
""" cancel historical data stream """
if contracts == None:
contracts = list(self.contracts.values())
elif not isinstance(contracts, list):
contracts = [contracts]
for contract in contracts:
# tickerId =... | python | def cancelHistoricalData(self, contracts=None):
if contracts == None:
contracts = list(self.contracts.values())
elif not isinstance(contracts, list):
contracts = [contracts]
for contract in contracts:
# tickerId = self.tickerId(contract.m_symbol)
... | [
"def",
"cancelHistoricalData",
"(",
"self",
",",
"contracts",
"=",
"None",
")",
":",
"if",
"contracts",
"==",
"None",
":",
"contracts",
"=",
"list",
"(",
"self",
".",
"contracts",
".",
"values",
"(",
")",
")",
"elif",
"not",
"isinstance",
"(",
"contracts... | cancel historical data stream | [
"cancel",
"historical",
"data",
"stream"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1931-L1941 |
242,964 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.getConId | def getConId(self, contract_identifier):
""" Get contracts conId """
details = self.contractDetails(contract_identifier)
if len(details["contracts"]) > 1:
return details["m_underConId"]
return details["m_summary"]["m_conId"] | python | def getConId(self, contract_identifier):
details = self.contractDetails(contract_identifier)
if len(details["contracts"]) > 1:
return details["m_underConId"]
return details["m_summary"]["m_conId"] | [
"def",
"getConId",
"(",
"self",
",",
"contract_identifier",
")",
":",
"details",
"=",
"self",
".",
"contractDetails",
"(",
"contract_identifier",
")",
"if",
"len",
"(",
"details",
"[",
"\"contracts\"",
"]",
")",
">",
"1",
":",
"return",
"details",
"[",
"\"... | Get contracts conId | [
"Get",
"contracts",
"conId"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1974-L1979 |
242,965 | ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createComboContract | def createComboContract(self, symbol, legs, currency="USD", exchange=None):
""" Used for ComboLegs. Expecting list of legs """
exchange = legs[0].m_exchange if exchange is None else exchange
contract_tuple = (symbol, "BAG", exchange, currency, "", 0.0, "")
contract = self.createContract(... | python | def createComboContract(self, symbol, legs, currency="USD", exchange=None):
exchange = legs[0].m_exchange if exchange is None else exchange
contract_tuple = (symbol, "BAG", exchange, currency, "", 0.0, "")
contract = self.createContract(contract_tuple, comboLegs=legs)
return contract | [
"def",
"createComboContract",
"(",
"self",
",",
"symbol",
",",
"legs",
",",
"currency",
"=",
"\"USD\"",
",",
"exchange",
"=",
"None",
")",
":",
"exchange",
"=",
"legs",
"[",
"0",
"]",
".",
"m_exchange",
"if",
"exchange",
"is",
"None",
"else",
"exchange",... | Used for ComboLegs. Expecting list of legs | [
"Used",
"for",
"ComboLegs",
".",
"Expecting",
"list",
"of",
"legs"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L2008-L2013 |
242,966 | ranaroussi/ezibpy | ezibpy/utils.py | order_to_dict | def order_to_dict(order):
"""Convert an IBPy Order object to a dict containing any non-default values."""
default = Order()
return {field: val for field, val in vars(order).items() if val != getattr(default, field, None)} | python | def order_to_dict(order):
default = Order()
return {field: val for field, val in vars(order).items() if val != getattr(default, field, None)} | [
"def",
"order_to_dict",
"(",
"order",
")",
":",
"default",
"=",
"Order",
"(",
")",
"return",
"{",
"field",
":",
"val",
"for",
"field",
",",
"val",
"in",
"vars",
"(",
"order",
")",
".",
"items",
"(",
")",
"if",
"val",
"!=",
"getattr",
"(",
"default"... | Convert an IBPy Order object to a dict containing any non-default values. | [
"Convert",
"an",
"IBPy",
"Order",
"object",
"to",
"a",
"dict",
"containing",
"any",
"non",
"-",
"default",
"values",
"."
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/utils.py#L204-L207 |
242,967 | ranaroussi/ezibpy | ezibpy/utils.py | contract_to_dict | def contract_to_dict(contract):
"""Convert an IBPy Contract object to a dict containing any non-default values."""
default = Contract()
return {field: val for field, val in vars(contract).items() if val != getattr(default, field, None)} | python | def contract_to_dict(contract):
default = Contract()
return {field: val for field, val in vars(contract).items() if val != getattr(default, field, None)} | [
"def",
"contract_to_dict",
"(",
"contract",
")",
":",
"default",
"=",
"Contract",
"(",
")",
"return",
"{",
"field",
":",
"val",
"for",
"field",
",",
"val",
"in",
"vars",
"(",
"contract",
")",
".",
"items",
"(",
")",
"if",
"val",
"!=",
"getattr",
"(",... | Convert an IBPy Contract object to a dict containing any non-default values. | [
"Convert",
"an",
"IBPy",
"Contract",
"object",
"to",
"a",
"dict",
"containing",
"any",
"non",
"-",
"default",
"values",
"."
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/utils.py#L212-L215 |
242,968 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _get_utm_code | def _get_utm_code(zone, direction):
""" Get UTM code given a zone and direction
Direction is encoded as NORTH=6, SOUTH=7, while zone is the UTM zone number zero-padded.
For instance, the code 32604 is returned for zone number 4, north direction.
:param zone: UTM zone number
:type zone: int
:pa... | python | def _get_utm_code(zone, direction):
dir_dict = {_Direction.NORTH: '6', _Direction.SOUTH: '7'}
return '{}{}{}'.format('32', dir_dict[direction], str(zone).zfill(2)) | [
"def",
"_get_utm_code",
"(",
"zone",
",",
"direction",
")",
":",
"dir_dict",
"=",
"{",
"_Direction",
".",
"NORTH",
":",
"'6'",
",",
"_Direction",
".",
"SOUTH",
":",
"'7'",
"}",
"return",
"'{}{}{}'",
".",
"format",
"(",
"'32'",
",",
"dir_dict",
"[",
"di... | Get UTM code given a zone and direction
Direction is encoded as NORTH=6, SOUTH=7, while zone is the UTM zone number zero-padded.
For instance, the code 32604 is returned for zone number 4, north direction.
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type... | [
"Get",
"UTM",
"code",
"given",
"a",
"zone",
"and",
"direction"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L225-L239 |
242,969 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _get_utm_name_value_pair | def _get_utm_name_value_pair(zone, direction=_Direction.NORTH):
""" Get name and code for UTM coordinates
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum, optional (default=NORTH)
:return: Name and code of UTM coordinates
:rtype: str,... | python | def _get_utm_name_value_pair(zone, direction=_Direction.NORTH):
name = 'UTM_{}{}'.format(zone, direction.value)
epsg = _get_utm_code(zone, direction)
return name, epsg | [
"def",
"_get_utm_name_value_pair",
"(",
"zone",
",",
"direction",
"=",
"_Direction",
".",
"NORTH",
")",
":",
"name",
"=",
"'UTM_{}{}'",
".",
"format",
"(",
"zone",
",",
"direction",
".",
"value",
")",
"epsg",
"=",
"_get_utm_code",
"(",
"zone",
",",
"direct... | Get name and code for UTM coordinates
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum, optional (default=NORTH)
:return: Name and code of UTM coordinates
:rtype: str, str | [
"Get",
"name",
"and",
"code",
"for",
"UTM",
"coordinates"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L242-L254 |
242,970 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _crs_parser | def _crs_parser(cls, value):
""" Parses user input for class CRS
:param cls: class object
:param value: user input for CRS
:type value: str, int or CRS
"""
parsed_value = value
if isinstance(parsed_value, int):
parsed_value = str(parsed_value)
if isinstance(parsed_value, str):
... | python | def _crs_parser(cls, value):
parsed_value = value
if isinstance(parsed_value, int):
parsed_value = str(parsed_value)
if isinstance(parsed_value, str):
parsed_value = parsed_value.strip('epsgEPSG: ')
return super(_BaseCRS, cls).__new__(cls, parsed_value) | [
"def",
"_crs_parser",
"(",
"cls",
",",
"value",
")",
":",
"parsed_value",
"=",
"value",
"if",
"isinstance",
"(",
"parsed_value",
",",
"int",
")",
":",
"parsed_value",
"=",
"str",
"(",
"parsed_value",
")",
"if",
"isinstance",
"(",
"parsed_value",
",",
"str"... | Parses user input for class CRS
:param cls: class object
:param value: user input for CRS
:type value: str, int or CRS | [
"Parses",
"user",
"input",
"for",
"class",
"CRS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L327-L339 |
242,971 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | DataSource.get_wfs_typename | def get_wfs_typename(cls, data_source):
""" Maps data source to string identifier for WFS
:param data_source: One of the supported data sources
:type: DataSource
:return: Product identifier for WFS
:rtype: str
"""
is_eocloud = SHConfig().is_eocloud_ogc_url()
... | python | def get_wfs_typename(cls, data_source):
is_eocloud = SHConfig().is_eocloud_ogc_url()
return {
cls.SENTINEL2_L1C: 'S2.TILE',
cls.SENTINEL2_L2A: 'SEN4CAP_S2L2A.TILE' if is_eocloud else 'DSS2',
cls.SENTINEL1_IW: 'S1.TILE' if is_eocloud else 'DSS3',
cls.SENTIN... | [
"def",
"get_wfs_typename",
"(",
"cls",
",",
"data_source",
")",
":",
"is_eocloud",
"=",
"SHConfig",
"(",
")",
".",
"is_eocloud_ogc_url",
"(",
")",
"return",
"{",
"cls",
".",
"SENTINEL2_L1C",
":",
"'S2.TILE'",
",",
"cls",
".",
"SENTINEL2_L2A",
":",
"'SEN4CAP_... | Maps data source to string identifier for WFS
:param data_source: One of the supported data sources
:type: DataSource
:return: Product identifier for WFS
:rtype: str | [
"Maps",
"data",
"source",
"to",
"string",
"identifier",
"for",
"WFS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L140-L166 |
242,972 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | DataSource.is_uswest_source | def is_uswest_source(self):
"""Checks if data source via Sentinel Hub services is available at US West server
Example: ``DataSource.LANDSAT8.is_uswest_source()`` or ``DataSource.is_uswest_source(DataSource.LANDSAT8)``
:param self: One of the supported data sources
:type self: DataSourc... | python | def is_uswest_source(self):
return not SHConfig().is_eocloud_ogc_url() and self.value[0] in [_Source.LANDSAT8, _Source.MODIS, _Source.DEM] | [
"def",
"is_uswest_source",
"(",
"self",
")",
":",
"return",
"not",
"SHConfig",
"(",
")",
".",
"is_eocloud_ogc_url",
"(",
")",
"and",
"self",
".",
"value",
"[",
"0",
"]",
"in",
"[",
"_Source",
".",
"LANDSAT8",
",",
"_Source",
".",
"MODIS",
",",
"_Source... | Checks if data source via Sentinel Hub services is available at US West server
Example: ``DataSource.LANDSAT8.is_uswest_source()`` or ``DataSource.is_uswest_source(DataSource.LANDSAT8)``
:param self: One of the supported data sources
:type self: DataSource
:return: ``True`` if data sou... | [
"Checks",
"if",
"data",
"source",
"via",
"Sentinel",
"Hub",
"services",
"is",
"available",
"at",
"US",
"West",
"server"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L192-L202 |
242,973 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | DataSource.get_available_sources | def get_available_sources(cls):
""" Returns which data sources are available for configured Sentinel Hub OGC URL
:return: List of available data sources
:rtype: list(sentinelhub.DataSource)
"""
if SHConfig().is_eocloud_ogc_url():
return [cls.SENTINEL2_L1C, cls.SENTIN... | python | def get_available_sources(cls):
if SHConfig().is_eocloud_ogc_url():
return [cls.SENTINEL2_L1C, cls.SENTINEL2_L2A, cls.SENTINEL2_L3B, cls.SENTINEL1_IW, cls.SENTINEL1_EW,
cls.SENTINEL1_EW_SH, cls.SENTINEL3, cls.SENTINEL5P, cls.LANDSAT5, cls.LANDSAT7, cls.LANDSAT8,
... | [
"def",
"get_available_sources",
"(",
"cls",
")",
":",
"if",
"SHConfig",
"(",
")",
".",
"is_eocloud_ogc_url",
"(",
")",
":",
"return",
"[",
"cls",
".",
"SENTINEL2_L1C",
",",
"cls",
".",
"SENTINEL2_L2A",
",",
"cls",
".",
"SENTINEL2_L3B",
",",
"cls",
".",
"... | Returns which data sources are available for configured Sentinel Hub OGC URL
:return: List of available data sources
:rtype: list(sentinelhub.DataSource) | [
"Returns",
"which",
"data",
"sources",
"are",
"available",
"for",
"configured",
"Sentinel",
"Hub",
"OGC",
"URL"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L205-L216 |
242,974 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _BaseCRS.get_utm_from_wgs84 | def get_utm_from_wgs84(lng, lat):
""" Convert from WGS84 to UTM coordinate system
:param lng: Longitude
:type lng: float
:param lat: Latitude
:type lat: float
:return: UTM coordinates
:rtype: tuple
"""
_, _, zone, _ = utm.from_latlon(lat, lng)
... | python | def get_utm_from_wgs84(lng, lat):
_, _, zone, _ = utm.from_latlon(lat, lng)
direction = 'N' if lat >= 0 else 'S'
return CRS['UTM_{}{}'.format(str(zone), direction)] | [
"def",
"get_utm_from_wgs84",
"(",
"lng",
",",
"lat",
")",
":",
"_",
",",
"_",
",",
"zone",
",",
"_",
"=",
"utm",
".",
"from_latlon",
"(",
"lat",
",",
"lng",
")",
"direction",
"=",
"'N'",
"if",
"lat",
">=",
"0",
"else",
"'S'",
"return",
"CRS",
"["... | Convert from WGS84 to UTM coordinate system
:param lng: Longitude
:type lng: float
:param lat: Latitude
:type lat: float
:return: UTM coordinates
:rtype: tuple | [
"Convert",
"from",
"WGS84",
"to",
"UTM",
"coordinate",
"system"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L263-L275 |
242,975 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | CustomUrlParam.has_value | def has_value(cls, value):
""" Tests whether CustomUrlParam contains a constant defined with a string `value`
:param value: The string representation of the enum constant
:type value: str
:return: `True` if there exists a constant with a string value `value`, `False` otherwise
:... | python | def has_value(cls, value):
return any(value.lower() == item.value.lower() for item in cls) | [
"def",
"has_value",
"(",
"cls",
",",
"value",
")",
":",
"return",
"any",
"(",
"value",
".",
"lower",
"(",
")",
"==",
"item",
".",
"value",
".",
"lower",
"(",
")",
"for",
"item",
"in",
"cls",
")"
] | Tests whether CustomUrlParam contains a constant defined with a string `value`
:param value: The string representation of the enum constant
:type value: str
:return: `True` if there exists a constant with a string value `value`, `False` otherwise
:rtype: bool | [
"Tests",
"whether",
"CustomUrlParam",
"contains",
"a",
"constant",
"defined",
"with",
"a",
"string",
"value"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L367-L375 |
242,976 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.canonical_extension | def canonical_extension(fmt_ext):
""" Canonical extension of file format extension
Converts the format extension fmt_ext into the canonical extension for that format. For example,
``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value
... | python | def canonical_extension(fmt_ext):
if MimeType.has_value(fmt_ext):
return fmt_ext
try:
return {
'tif': MimeType.TIFF.value,
'jpeg': MimeType.JPG.value,
'hdf5': MimeType.HDF.value,
'h5': MimeType.HDF.value
... | [
"def",
"canonical_extension",
"(",
"fmt_ext",
")",
":",
"if",
"MimeType",
".",
"has_value",
"(",
"fmt_ext",
")",
":",
"return",
"fmt_ext",
"try",
":",
"return",
"{",
"'tif'",
":",
"MimeType",
".",
"TIFF",
".",
"value",
",",
"'jpeg'",
":",
"MimeType",
"."... | Canonical extension of file format extension
Converts the format extension fmt_ext into the canonical extension for that format. For example,
``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value
:param fmt_ext: A string representing an ex... | [
"Canonical",
"extension",
"of",
"file",
"format",
"extension"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L424-L445 |
242,977 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.is_image_format | def is_image_format(self):
""" Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise... | python | def is_image_format(self):
return self in frozenset([MimeType.TIFF, MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f, MimeType.PNG,
MimeType.JP2, MimeType.JPG]) | [
"def",
"is_image_format",
"(",
"self",
")",
":",
"return",
"self",
"in",
"frozenset",
"(",
"[",
"MimeType",
".",
"TIFF",
",",
"MimeType",
".",
"TIFF_d8",
",",
"MimeType",
".",
"TIFF_d16",
",",
"MimeType",
".",
"TIFF_d32f",
",",
"MimeType",
".",
"PNG",
",... | Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool | [
"Checks",
"whether",
"file",
"format",
"is",
"an",
"image",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L447-L458 |
242,978 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.is_tiff_format | def is_tiff_format(self):
""" Checks whether file format is a TIFF image format
Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherw... | python | def is_tiff_format(self):
return self in frozenset([MimeType.TIFF, MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]) | [
"def",
"is_tiff_format",
"(",
"self",
")",
":",
"return",
"self",
"in",
"frozenset",
"(",
"[",
"MimeType",
".",
"TIFF",
",",
"MimeType",
".",
"TIFF_d8",
",",
"MimeType",
".",
"TIFF_d16",
",",
"MimeType",
".",
"TIFF_d32f",
"]",
")"
] | Checks whether file format is a TIFF image format
Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool | [
"Checks",
"whether",
"file",
"format",
"is",
"a",
"TIFF",
"image",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L460-L470 |
242,979 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.get_string | def get_string(self):
""" Get file format as string
:return: String describing the file format
:rtype: str
"""
if self in [MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]:
return 'image/{}'.format(self.value)
if self is MimeType.JP2:
retu... | python | def get_string(self):
if self in [MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]:
return 'image/{}'.format(self.value)
if self is MimeType.JP2:
return 'image/jpeg2000'
if self in [MimeType.RAW, MimeType.REQUESTS_RESPONSE]:
return self.value
r... | [
"def",
"get_string",
"(",
"self",
")",
":",
"if",
"self",
"in",
"[",
"MimeType",
".",
"TIFF_d8",
",",
"MimeType",
".",
"TIFF_d16",
",",
"MimeType",
".",
"TIFF_d32f",
"]",
":",
"return",
"'image/{}'",
".",
"format",
"(",
"self",
".",
"value",
")",
"if",... | Get file format as string
:return: String describing the file format
:rtype: str | [
"Get",
"file",
"format",
"as",
"string"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L483-L495 |
242,980 | sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.get_expected_max_value | def get_expected_max_value(self):
""" Returns max value of image `MimeType` format and raises an error if it is not an image format
Note: For `MimeType.TIFF_d32f` it will return ``1.0`` as that is expected maximum for an image even though it
could be higher.
:return: A maximum value of... | python | def get_expected_max_value(self):
try:
return {
MimeType.TIFF: 65535,
MimeType.TIFF_d8: 255,
MimeType.TIFF_d16: 65535,
MimeType.TIFF_d32f: 1.0,
MimeType.PNG: 255,
MimeType.JPG: 255,
MimeTy... | [
"def",
"get_expected_max_value",
"(",
"self",
")",
":",
"try",
":",
"return",
"{",
"MimeType",
".",
"TIFF",
":",
"65535",
",",
"MimeType",
".",
"TIFF_d8",
":",
"255",
",",
"MimeType",
".",
"TIFF_d16",
":",
"65535",
",",
"MimeType",
".",
"TIFF_d32f",
":",... | Returns max value of image `MimeType` format and raises an error if it is not an image format
Note: For `MimeType.TIFF_d32f` it will return ``1.0`` as that is expected maximum for an image even though it
could be higher.
:return: A maximum value of specified image format
:rtype: int or... | [
"Returns",
"max",
"value",
"of",
"image",
"MimeType",
"format",
"and",
"raises",
"an",
"error",
"if",
"it",
"is",
"not",
"an",
"image",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L497-L518 |
242,981 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcService._filter_dates | def _filter_dates(dates, time_difference):
"""
Filters out dates within time_difference, preserving only the oldest date.
:param dates: a list of datetime objects
:param time_difference: a ``datetime.timedelta`` representing the time difference threshold
:return: an ordered list... | python | def _filter_dates(dates, time_difference):
LOGGER.debug("dates=%s", dates)
if len(dates) <= 1:
return dates
sorted_dates = sorted(dates)
separate_dates = [sorted_dates[0]]
for curr_date in sorted_dates[1:]:
if curr_date - separate_dates[-1] > time_diffe... | [
"def",
"_filter_dates",
"(",
"dates",
",",
"time_difference",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"dates=%s\"",
",",
"dates",
")",
"if",
"len",
"(",
"dates",
")",
"<=",
"1",
":",
"return",
"dates",
"sorted_dates",
"=",
"sorted",
"(",
"dates",
")",
... | Filters out dates within time_difference, preserving only the oldest date.
:param dates: a list of datetime objects
:param time_difference: a ``datetime.timedelta`` representing the time difference threshold
:return: an ordered list of datetimes `d1<=d2<=...<=dn` such that `d[i+1]-di > time_dif... | [
"Filters",
"out",
"dates",
"within",
"time_difference",
"preserving",
"only",
"the",
"oldest",
"date",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L44-L65 |
242,982 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcService._sentinel1_product_check | def _sentinel1_product_check(product_id, data_source):
"""Checks if Sentinel-1 product ID matches Sentinel-1 DataSource configuration
:param product_id: Sentinel-1 product ID
:type product_id: str
:param data_source: One of the supported Sentinel-1 data sources
:type data_source... | python | def _sentinel1_product_check(product_id, data_source):
props = product_id.split('_')
acquisition, resolution, polarisation = props[1], props[2][3], props[3][2:4]
if acquisition in ['IW', 'EW'] and resolution in ['M', 'H'] and polarisation in ['DV', 'DH', 'SV', 'SH']:
return acquisiti... | [
"def",
"_sentinel1_product_check",
"(",
"product_id",
",",
"data_source",
")",
":",
"props",
"=",
"product_id",
".",
"split",
"(",
"'_'",
")",
"acquisition",
",",
"resolution",
",",
"polarisation",
"=",
"props",
"[",
"1",
"]",
",",
"props",
"[",
"2",
"]",
... | Checks if Sentinel-1 product ID matches Sentinel-1 DataSource configuration
:param product_id: Sentinel-1 product ID
:type product_id: str
:param data_source: One of the supported Sentinel-1 data sources
:type data_source: constants.DataSource
:return: True if data_source contai... | [
"Checks",
"if",
"Sentinel",
"-",
"1",
"product",
"ID",
"matches",
"Sentinel",
"-",
"1",
"DataSource",
"configuration"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L68-L83 |
242,983 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_url | def get_url(self, request, *, date=None, size_x=None, size_y=None, geometry=None):
""" Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request... | python | def get_url(self, request, *, date=None, size_x=None, size_y=None, geometry=None):
url = self.get_base_url(request)
authority = self.instance_id if hasattr(self, 'instance_id') else request.theme
params = self._get_common_url_parameters(request)
if request.service_type in (ServiceType.W... | [
"def",
"get_url",
"(",
"self",
",",
"request",
",",
"*",
",",
"date",
"=",
"None",
",",
"size_x",
"=",
"None",
",",
"size_y",
"=",
"None",
",",
"geometry",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"get_base_url",
"(",
"request",
")",
"author... | Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type dat... | [
"Returns",
"url",
"to",
"Sentinel",
"Hub",
"s",
"OGC",
"service",
"for",
"the",
"product",
"specified",
"by",
"the",
"OgcRequest",
"and",
"date",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L121-L150 |
242,984 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_base_url | def get_base_url(self, request):
""" Creates base url string.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: base string for url to Sentinel Hub's OGC service for this product.
... | python | def get_base_url(self, request):
url = self.base_url + request.service_type.value
# These 2 lines are temporal and will be removed after the use of uswest url wont be required anymore:
if hasattr(request, 'data_source') and request.data_source.is_uswest_source():
url = 'https://servi... | [
"def",
"get_base_url",
"(",
"self",
",",
"request",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"request",
".",
"service_type",
".",
"value",
"# These 2 lines are temporal and will be removed after the use of uswest url wont be required anymore:",
"if",
"hasattr",
... | Creates base url string.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: base string for url to Sentinel Hub's OGC service for this product.
:rtype: str | [
"Creates",
"base",
"url",
"string",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L152-L168 |
242,985 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService._get_common_url_parameters | def _get_common_url_parameters(request):
""" Returns parameters common dictionary for WMS, WCS and FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: dictionary with param... | python | def _get_common_url_parameters(request):
params = {
'SERVICE': request.service_type.value
}
if hasattr(request, 'maxcc'):
params['MAXCC'] = 100.0 * request.maxcc
if hasattr(request, 'custom_url_params') and request.custom_url_params is not None:
para... | [
"def",
"_get_common_url_parameters",
"(",
"request",
")",
":",
"params",
"=",
"{",
"'SERVICE'",
":",
"request",
".",
"service_type",
".",
"value",
"}",
"if",
"hasattr",
"(",
"request",
",",
"'maxcc'",
")",
":",
"params",
"[",
"'MAXCC'",
"]",
"=",
"100.0",
... | Returns parameters common dictionary for WMS, WCS and FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: dictionary with parameters
:rtype: dict | [
"Returns",
"parameters",
"common",
"dictionary",
"for",
"WMS",
"WCS",
"and",
"FIS",
"request",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L171-L209 |
242,986 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService._get_wms_wcs_url_parameters | def _get_wms_wcs_url_parameters(request, date):
""" Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition dat... | python | def _get_wms_wcs_url_parameters(request, date):
params = {
'BBOX': str(request.bbox.reverse()) if request.bbox.crs is CRS.WGS84 else str(request.bbox),
'FORMAT': MimeType.get_string(request.image_format),
'CRS': CRS.ogc_string(request.bbox.crs),
}
if date is ... | [
"def",
"_get_wms_wcs_url_parameters",
"(",
"request",
",",
"date",
")",
":",
"params",
"=",
"{",
"'BBOX'",
":",
"str",
"(",
"request",
".",
"bbox",
".",
"reverse",
"(",
")",
")",
"if",
"request",
".",
"bbox",
".",
"crs",
"is",
"CRS",
".",
"WGS84",
"e... | Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
... | [
"Returns",
"parameters",
"common",
"dictionary",
"for",
"WMS",
"and",
"WCS",
"request",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L212-L235 |
242,987 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService._get_fis_parameters | def _get_fis_parameters(request, geometry):
""" Returns parameters dictionary for FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param geometry: list of bounding boxes or geome... | python | def _get_fis_parameters(request, geometry):
date_interval = parse_time_interval(request.time)
params = {
'CRS': CRS.ogc_string(geometry.crs),
'LAYER': request.layer,
'RESOLUTION': request.resolution,
'TIME': '{}/{}'.format(date_interval[0], date_interval[... | [
"def",
"_get_fis_parameters",
"(",
"request",
",",
"geometry",
")",
":",
"date_interval",
"=",
"parse_time_interval",
"(",
"request",
".",
"time",
")",
"params",
"=",
"{",
"'CRS'",
":",
"CRS",
".",
"ogc_string",
"(",
"geometry",
".",
"crs",
")",
",",
"'LAY... | Returns parameters dictionary for FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param geometry: list of bounding boxes or geometries
:type geometry: list of BBox or Geometry
... | [
"Returns",
"parameters",
"dictionary",
"for",
"FIS",
"request",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L280-L315 |
242,988 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_filename | def get_filename(request, date, size_x, size_y):
""" Get filename location
Returns the filename's location on disk where data is or is going to be stored.
The files are stored in the folder specified by the user when initialising OGC-type
of request. The name of the file has the followi... | python | def get_filename(request, date, size_x, size_y):
filename = '_'.join([
str(request.service_type.value),
request.layer,
str(request.bbox.crs),
str(request.bbox).replace(',', '_'),
'' if date is None else date.strftime("%Y-%m-%dT%H-%M-%S"),
'... | [
"def",
"get_filename",
"(",
"request",
",",
"date",
",",
"size_x",
",",
"size_y",
")",
":",
"filename",
"=",
"'_'",
".",
"join",
"(",
"[",
"str",
"(",
"request",
".",
"service_type",
".",
"value",
")",
",",
"request",
".",
"layer",
",",
"str",
"(",
... | Get filename location
Returns the filename's location on disk where data is or is going to be stored.
The files are stored in the folder specified by the user when initialising OGC-type
of request. The name of the file has the following structure:
{service_type}_{layer}_{crs}_{bbox}_{t... | [
"Get",
"filename",
"location"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L318-L352 |
242,989 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.filename_add_custom_url_params | def filename_add_custom_url_params(filename, request):
""" Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcReq... | python | def filename_add_custom_url_params(filename, request):
if hasattr(request, 'custom_url_params') and request.custom_url_params is not None:
for param, value in sorted(request.custom_url_params.items(),
key=lambda parameter_item: parameter_item[0].value):
... | [
"def",
"filename_add_custom_url_params",
"(",
"filename",
",",
"request",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"'custom_url_params'",
")",
"and",
"request",
".",
"custom_url_params",
"is",
"not",
"None",
":",
"for",
"param",
",",
"value",
"in",
"sor... | Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: Filename with custom url p... | [
"Adds",
"custom",
"url",
"parameters",
"to",
"filename",
"string"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L355-L370 |
242,990 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.finalize_filename | def finalize_filename(filename, file_format=None):
""" Replaces invalid characters in filename string, adds image extension and reduces filename length
:param filename: Incomplete filename string
:type filename: str
:param file_format: Format which will be used for filename extension
... | python | def finalize_filename(filename, file_format=None):
for char in [' ', '/', '\\', '|', ';', ':', '\n', '\t']:
filename = filename.replace(char, '')
if file_format:
suffix = str(file_format.value)
if file_format.is_tiff_format() and file_format is not MimeType.TIFF:
... | [
"def",
"finalize_filename",
"(",
"filename",
",",
"file_format",
"=",
"None",
")",
":",
"for",
"char",
"in",
"[",
"' '",
",",
"'/'",
",",
"'\\\\'",
",",
"'|'",
",",
"';'",
",",
"':'",
",",
"'\\n'",
",",
"'\\t'",
"]",
":",
"filename",
"=",
"filename",... | Replaces invalid characters in filename string, adds image extension and reduces filename length
:param filename: Incomplete filename string
:type filename: str
:param file_format: Format which will be used for filename extension
:type file_format: MimeType
:return: Final filena... | [
"Replaces",
"invalid",
"characters",
"in",
"filename",
"string",
"adds",
"image",
"extension",
"and",
"reduces",
"filename",
"length"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L373-L396 |
242,991 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_dates | def get_dates(self, request):
""" Get available Sentinel-2 acquisitions at least time_difference apart
List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified
time interval. When a single time is specified the request will return that specific date... | python | def get_dates(self, request):
if DataSource.is_timeless(request.data_source):
return [None]
date_interval = parse_time_interval(request.time)
LOGGER.debug('date_interval=%s', date_interval)
if request.wfs_iterator is None:
self.wfs_iterator = WebFeatureService(... | [
"def",
"get_dates",
"(",
"self",
",",
"request",
")",
":",
"if",
"DataSource",
".",
"is_timeless",
"(",
"request",
".",
"data_source",
")",
":",
"return",
"[",
"None",
"]",
"date_interval",
"=",
"parse_time_interval",
"(",
"request",
".",
"time",
")",
"LOG... | Get available Sentinel-2 acquisitions at least time_difference apart
List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified
time interval. When a single time is specified the request will return that specific date, if it exists.
If a time range is... | [
"Get",
"available",
"Sentinel",
"-",
"2",
"acquisitions",
"at",
"least",
"time_difference",
"apart"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L398-L432 |
242,992 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_image_dimensions | def get_image_dimensions(request):
"""
Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str)
"""
if... | python | def get_image_dimensions(request):
if request.service_type is ServiceType.WCS or (isinstance(request.size_x, int) and
isinstance(request.size_y, int)):
return request.size_x, request.size_y
if not isinstance(request.size_x, int) and not ... | [
"def",
"get_image_dimensions",
"(",
"request",
")",
":",
"if",
"request",
".",
"service_type",
"is",
"ServiceType",
".",
"WCS",
"or",
"(",
"isinstance",
"(",
"request",
".",
"size_x",
",",
"int",
")",
"and",
"isinstance",
"(",
"request",
".",
"size_y",
","... | Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str) | [
"Verifies",
"or",
"calculates",
"image",
"dimensions",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L435-L454 |
242,993 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | WebFeatureService._fetch_features | def _fetch_features(self):
"""Collects data from WFS service
:return: dictionary containing info about product tiles
:rtype: dict
"""
if self.feature_offset is None:
return
main_url = '{}{}/{}?'.format(self.base_url, ServiceType.WFS.value, self.instance_id)
... | python | def _fetch_features(self):
if self.feature_offset is None:
return
main_url = '{}{}/{}?'.format(self.base_url, ServiceType.WFS.value, self.instance_id)
params = {'SERVICE': ServiceType.WFS.value,
'REQUEST': 'GetFeature',
'TYPENAMES': DataSource.ge... | [
"def",
"_fetch_features",
"(",
"self",
")",
":",
"if",
"self",
".",
"feature_offset",
"is",
"None",
":",
"return",
"main_url",
"=",
"'{}{}/{}?'",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"ServiceType",
".",
"WFS",
".",
"value",
",",
"self",
".",... | Collects data from WFS service
:return: dictionary containing info about product tiles
:rtype: dict | [
"Collects",
"data",
"from",
"WFS",
"service"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L524-L558 |
242,994 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | WebFeatureService.get_dates | def get_dates(self):
""" Returns a list of acquisition times from tile info data
:return: List of acquisition times in the order returned by WFS service.
:rtype: list(datetime.datetime)
"""
return [datetime.datetime.strptime('{}T{}'.format(tile_info['properties']['date'],
... | python | def get_dates(self):
return [datetime.datetime.strptime('{}T{}'.format(tile_info['properties']['date'],
tile_info['properties']['time'].split('.')[0]),
'%Y-%m-%dT%H:%M:%S') for tile_info in self] | [
"def",
"get_dates",
"(",
"self",
")",
":",
"return",
"[",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"'{}T{}'",
".",
"format",
"(",
"tile_info",
"[",
"'properties'",
"]",
"[",
"'date'",
"]",
",",
"tile_info",
"[",
"'properties'",
"]",
"[",
"'time... | Returns a list of acquisition times from tile info data
:return: List of acquisition times in the order returned by WFS service.
:rtype: list(datetime.datetime) | [
"Returns",
"a",
"list",
"of",
"acquisition",
"times",
"from",
"tile",
"info",
"data"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L560-L568 |
242,995 | sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | WebFeatureService._parse_tile_url | def _parse_tile_url(tile_url):
""" Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int)
"""
props = tile_url.rsplit('/', 7)... | python | def _parse_tile_url(tile_url):
props = tile_url.rsplit('/', 7)
return ''.join(props[1:4]), '-'.join(props[4:7]), int(props[7]) | [
"def",
"_parse_tile_url",
"(",
"tile_url",
")",
":",
"props",
"=",
"tile_url",
".",
"rsplit",
"(",
"'/'",
",",
"7",
")",
"return",
"''",
".",
"join",
"(",
"props",
"[",
"1",
":",
"4",
"]",
")",
",",
"'-'",
".",
"join",
"(",
"props",
"[",
"4",
"... | Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int) | [
"Extracts",
"tile",
"name",
"data",
"and",
"AWS",
"index",
"from",
"tile",
"URL"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L587-L596 |
242,996 | sentinel-hub/sentinelhub-py | sentinelhub/time_utils.py | get_dates_in_range | def get_dates_in_range(start_date, end_date):
""" Get all dates within input start and end date in ISO 8601 format
:param start_date: start date in ISO 8601 format
:type start_date: str
:param end_date: end date in ISO 8601 format
:type end_date: str
:return: list of dates between start_date an... | python | def get_dates_in_range(start_date, end_date):
start_dt = iso_to_datetime(start_date)
end_dt = iso_to_datetime(end_date)
num_days = int((end_dt - start_dt).days)
return [datetime_to_iso(start_dt + datetime.timedelta(i)) for i in range(num_days + 1)] | [
"def",
"get_dates_in_range",
"(",
"start_date",
",",
"end_date",
")",
":",
"start_dt",
"=",
"iso_to_datetime",
"(",
"start_date",
")",
"end_dt",
"=",
"iso_to_datetime",
"(",
"end_date",
")",
"num_days",
"=",
"int",
"(",
"(",
"end_dt",
"-",
"start_dt",
")",
"... | Get all dates within input start and end date in ISO 8601 format
:param start_date: start date in ISO 8601 format
:type start_date: str
:param end_date: end date in ISO 8601 format
:type end_date: str
:return: list of dates between start_date and end_date in ISO 8601 format
:rtype: list of str | [
"Get",
"all",
"dates",
"within",
"input",
"start",
"and",
"end",
"date",
"in",
"ISO",
"8601",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/time_utils.py#L12-L25 |
242,997 | sentinel-hub/sentinelhub-py | sentinelhub/time_utils.py | iso_to_datetime | def iso_to_datetime(date):
""" Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
... | python | def iso_to_datetime(date):
chunks = list(map(int, date.split('T')[0].split('-')))
return datetime.datetime(chunks[0], chunks[1], chunks[2]) | [
"def",
"iso_to_datetime",
"(",
"date",
")",
":",
"chunks",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"date",
".",
"split",
"(",
"'T'",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'-'",
")",
")",
")",
"return",
"datetime",
".",
"datetime",
"(",
"chunk... | Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
:rtype: datetime | [
"Convert",
"ISO",
"8601",
"time",
"format",
"to",
"datetime",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/time_utils.py#L56-L68 |
242,998 | sentinel-hub/sentinelhub-py | sentinelhub/time_utils.py | datetime_to_iso | def datetime_to_iso(date, only_date=True):
""" Convert datetime format to ISO 8601 time format
This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format,
e.g. ``2017-09-14``
:param date: datetime instance to convert
:type date: datetime
:param ... | python | def datetime_to_iso(date, only_date=True):
if only_date:
return date.isoformat().split('T')[0]
return date.isoformat() | [
"def",
"datetime_to_iso",
"(",
"date",
",",
"only_date",
"=",
"True",
")",
":",
"if",
"only_date",
":",
"return",
"date",
".",
"isoformat",
"(",
")",
".",
"split",
"(",
"'T'",
")",
"[",
"0",
"]",
"return",
"date",
".",
"isoformat",
"(",
")"
] | Convert datetime format to ISO 8601 time format
This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format,
e.g. ``2017-09-14``
:param date: datetime instance to convert
:type date: datetime
:param only_date: whether to return date only or also time... | [
"Convert",
"datetime",
"format",
"to",
"ISO",
"8601",
"time",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/time_utils.py#L71-L86 |
242,999 | sentinel-hub/sentinelhub-py | sentinelhub/commands.py | aws | def aws(product, tile, folder, redownload, info, entire, bands, l2a):
"""Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads.
\b
Examples with Sentinel-2 L1C data:
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551
... | python | def aws(product, tile, folder, redownload, info, entire, bands, l2a):
band_list = None if bands is None else bands.split(',')
data_source = DataSource.SENTINEL2_L2A if l2a else DataSource.SENTINEL2_L1C
if info:
if product is None:
click.echo(get_safe_format(tile=tile, entire_product=enti... | [
"def",
"aws",
"(",
"product",
",",
"tile",
",",
"folder",
",",
"redownload",
",",
"info",
",",
"entire",
",",
"bands",
",",
"l2a",
")",
":",
"band_list",
"=",
"None",
"if",
"bands",
"is",
"None",
"else",
"bands",
".",
"split",
"(",
"','",
")",
"dat... | Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads.
\b
Examples with Sentinel-2 L1C data:
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_201... | [
"Download",
"Sentinel",
"-",
"2",
"data",
"from",
"Sentinel",
"-",
"2",
"on",
"AWS",
"to",
"ESA",
"SAFE",
"format",
".",
"Download",
"uses",
"multiple",
"threads",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/commands.py#L38-L67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.