markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
The helper function `toplevel_defs()` helps saving and restoring the environment before and after redefining the function under repair.
class Repairer(Repairer): def toplevel_defs(self, tree: ast.AST) -> List[str]: """Return a list of names of defined functions and classes in `tree`""" visitor = DefinitionVisitor() visitor.visit(tree) assert hasattr(visitor, 'definitions') return visitor.definitions class Def...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Here's an example for `fitness()`:
repairer = Repairer(middle_debugger, log=1) good_fitness = repairer.fitness(middle_tree()) good_fitness # ignore assert good_fitness >= 0.99, "fitness() failed" bad_middle_tree = ast.parse("def middle(x, y, z): return x") bad_fitness = repairer.fitness(bad_middle_tree) bad_fitness # ignore assert bad_fitness < 0.5, "fi...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
RepairingNow for the actual `repair()` method, which creates a `population` and then evolves it until the fitness is 1.0 or the given number of iterations is spent.
import traceback class Repairer(Repairer): def initial_population(self, size: int) -> List[ast.AST]: """Return an initial population of size `size`""" return [self.target_tree] + \ [self.mutator.mutate(copy.deepcopy(self.target_tree)) for i in range(size - 1)] def re...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
EvolvingThe evolution of our population takes place in the `evolve()` method. In contrast to the `evolve_middle()` function, above, we use crossover to create the offspring, which we still mutate afterwards.
class Repairer(Repairer): def evolve(self, population: List[ast.AST]) -> List[ast.AST]: """Evolve the candidate population by mutating and crossover.""" n = len(population) # Create offspring as crossover of parents offspring: List[ast.AST] = [] while len(offspring) < n: ...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
A second difference is that we not only sort by fitness, but also by tree size – with equal fitness, a smaller tree thus will be favored. This helps keeping fixes and patches small.
class Repairer(Repairer): def fitness_key(self, tree: ast.AST) -> Tuple[float, int]: """Key to be used for sorting the population""" tree_size = len([node for node in ast.walk(tree)]) return (self.fitness(tree), -tree_size)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
SimplifyingThe last step in repairing is simplifying the code. As demonstrated in the chapter on [reducing failure-inducing inputs](DeltaDebugger.ipynb), we can use delta debugging on code to get rid of superfluous statements. To this end, we convert the tree to lines, run delta debugging on them, and then convert it ...
class Repairer(Repairer): def reduce(self, tree: ast.AST) -> ast.AST: """Simplify `tree` using delta debugging.""" original_fitness = self.fitness(tree) source_lines = astor.to_source(tree).split('\n') with self.reducer: self.test_reduce(source_lines, original_fitness) ...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
As dicussed above, we simplify the code by having the test function (`test_reduce()`) declare reaching the maximum fitness obtained so far as a "failure". Delta debugging will then simplify the input as long as the "failure" (and hence the maximum fitness obtained) persists.
class Repairer(Repairer): def test_reduce(self, source_lines: List[str], original_fitness: float) -> None: """Test function for delta debugging.""" try: source = "\n".join(source_lines) tree = ast.parse(source) fitness = self.fitness(tree) assert fitn...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
End of Excursion Repairer in ActionLet us go and apply `Repairer` in practice. We initialize it with `middle_debugger`, which has (still) collected the passing and failing runs for `middle_test()`. We also set `log` for some diagnostics along the way.
repairer = Repairer(middle_debugger, log=True)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
We now invoke `repair()` to evolve our population. After a few iterations, we find a best tree with perfect fitness.
best_tree, fitness = repairer.repair() print_content(astor.to_source(best_tree), '.py') fitness
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Again, we have a perfect solution. Here, we did not even need to simplify the code in the last iteration, as our `fitness_key()` function favors smaller implementations. Removing HTML MarkupLet us apply `Repairer` on our other ongoing example, namely `remove_html_markup()`.
def remove_html_markup(s): # type: ignore tag = False quote = False out = "" for c in s: if c == '<' and not quote: tag = True elif c == '>' and not quote: tag = False elif c == '"' or c == "'" and tag: quote = not quote elif not tag:...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
To run `Repairer` on `remove_html_markup()`, we need a test and a test suite. `remove_html_markup_test()` raises an exception if applying `remove_html_markup()` on the given `html` string does not yield the `plain` string.
def remove_html_markup_test(html: str, plain: str) -> None: outcome = remove_html_markup(html) assert outcome == plain, \ f"Got {repr(outcome)}, expected {repr(plain)}"
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Now for the test suite. We use a simple fuzzing scheme to create dozens of passing and failing test cases in `REMOVE_HTML_PASSING_TESTCASES` and `REMOVE_HTML_FAILING_TESTCASES`, respectively. Excursion: Creating HTML Test Cases
def random_string(length: int = 5, start: int = ord(' '), end: int = ord('~')) -> str: return "".join(chr(random.randrange(start, end + 1)) for i in range(length)) random_string() def random_id(length: int = 2) -> str: return random_string(start=ord('a'), end=ord('z')) random_id() def random_plain() -> str: ...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
End of Excursion Here is a passing test case:
REMOVE_HTML_PASSING_TESTCASES[0] html, plain = REMOVE_HTML_PASSING_TESTCASES[0] remove_html_markup_test(html, plain)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Here is a failing test case (containing a double quote in the plain text)
REMOVE_HTML_FAILING_TESTCASES[0] with ExpectError(): html, plain = REMOVE_HTML_FAILING_TESTCASES[0] remove_html_markup_test(html, plain)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
We run our tests, collecting the outcomes in `html_debugger`.
html_debugger = OchiaiDebugger() for html, plain in (REMOVE_HTML_PASSING_TESTCASES + REMOVE_HTML_FAILING_TESTCASES): with html_debugger: remove_html_markup_test(html, plain)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
The suspiciousness distribution will not be of much help here – pretty much all lines in `remove_html_markup()` have the same suspiciousness.
html_debugger
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Let us create our repairer and run it.
html_repairer = Repairer(html_debugger, log=True) best_tree, fitness = html_repairer.repair(iterations=20)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
We see that the "best" code is still our original code, with no changes. And we can set `iterations` to 50, 100, 200... – our `Repairer` won't be able to repair it.
quiz("Why couldn't `Repairer()` repair `remove_html_markup()`?", [ "The population is too small!", "The suspiciousness is too evenly distributed!", "We need more test cases!", "We need more iterations!", "There is no statement in the source with a correct condition!", ...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
You can explore all of the hypotheses above by changing the appropriate parameters, but you won't be able to change the outcome. The problem is that, unlike `middle()`, there is no statement (or combination thereof) in `remove_html_markup()` that could be used to make the failure go away. For this, we need to mutate an...
def all_conditions(trees: Union[ast.AST, List[ast.AST]], tp: Optional[Type] = None) -> List[ast.expr]: """ Return all conditions from the AST (or AST list) `trees`. If `tp` is given, return only elements of that type. """ if not isinstance(trees, list): assert isinstance(...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
`all_conditions()` uses a `ConditionVisitor` class to walk the tree and collect the conditions:
class ConditionVisitor(NodeVisitor): def __init__(self) -> None: self.conditions: List[ast.expr] = [] self.conditions_seen: Set[str] = set() super().__init__() def add_conditions(self, node: ast.AST, attr: str) -> None: elems = getattr(node, attr, []) if not isinstance(e...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Here are all the conditions in `remove_html_markup()`. This is some material to construct new conditions from.
[astor.to_source(cond).strip() for cond in all_conditions(remove_html_markup_tree())]
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Mutating ConditionsHere comes our `ConditionMutator` class. We subclass from `StatementMutator` and set an attribute `self.conditions` containing all the conditions in the source. The method `choose_condition()` randomly picks a condition.
class ConditionMutator(StatementMutator): """Mutate conditions in an AST""" def __init__(self, *args: Any, **kwargs: Any) -> None: """Constructor. Arguments are as with `StatementMutator` constructor.""" super().__init__(*args, **kwargs) self.conditions = all_conditions(self.source) ...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
The actual mutation takes place in the `swap()` method. If the node to be replaced has a `test` attribute (i.e. a controlling predicate), then we pick a random condition `cond` from the source and randomly chose from:* **set**: We change `test` to `cond`.* **not**: We invert `test`.* **and**: We replace `test` by `cond...
class ConditionMutator(ConditionMutator): def choose_bool_op(self) -> str: return random.choice(['set', 'not', 'and', 'or']) def swap(self, node: ast.AST) -> ast.AST: """Replace `node` condition by a condition from `source`""" if not hasattr(node, 'test'): return super().swa...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
We can use the mutator just like `StatementMutator`, except that some of the mutations will also include new conditions:
mutator = ConditionMutator(source=all_statements(remove_html_markup_tree()), log=True) for i in range(10): new_tree = mutator.mutate(remove_html_markup_tree())
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Let us put our new mutator to action, again in a `Repairer()`. To activate it, all we need to do is to pass it as `mutator_class` keyword argument.
condition_repairer = Repairer(html_debugger, mutator_class=ConditionMutator, log=2)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
We might need more iterations for this one. Let us see...
best_tree, fitness = condition_repairer.repair(iterations=200) repaired_source = astor.to_source(best_tree) print_content(repaired_source, '.py')
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Success again! We have automatically repaired `remove_html_markup()` – the resulting code passes all tests, including those that were previously failing. Again, we can present the fix as a patch:
original_source = astor.to_source(remove_html_markup_tree()) for patch in diff(original_source, repaired_source): print_patch(patch)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
However, looking at the patch, one may come up with doubts.
quiz("Is this actually the best solution?", [ "Yes, sure, of course. Why?", "Err - what happened to single quotes?" ], 1 << 1)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Indeed – our solution does not seem to handle single quotes anymore. Why is that so?
quiz("Why aren't single quotes handled in the solution?", [ "Because they're not important. I mean, who uses 'em anyway?", "Because they are not part of our tests? " "Let me look up how they are constructed..." ], 1 << 1)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Correct! Our test cases do not include single quotes – at least not in the interior of HTML tags – and thus, automatic repair did not care to preserve their handling. How can we fix this? An easy way is to include an appropriate test case in our set – a test case that passes with the original `remove_html_markup()`, ye...
with html_debugger: remove_html_markup_test("<foo quote='>abc'>me</foo>", "me")
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Let us repeat the repair with the extended test set:
best_tree, fitness = condition_repairer.repair(iterations=200)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Here is the final tree:
print_content(astor.to_source(best_tree), '.py')
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
And here is its fitness:
fitness
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
The revised candidate now passes _all_ tests (including the tricky quote test we added last). Its condition now properly checks for `tag` _and_ both quotes. (The `tag` inside the parentheses is still redundant, but so be it.) From this example, we can learn a few lessons about the possibilities and risks of automated r...
# ignore print_content(middle_source, '.py')
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
We set up a function `middle_test()` that tests it. The `middle_debugger` collects testcases and outcomes:
middle_debugger = OchiaiDebugger() for x, y, z in MIDDLE_PASSING_TESTCASES + MIDDLE_FAILING_TESTCASES: with middle_debugger: middle_test(x, y, z)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
The repairer attempts to repair the invoked function (`middle()`). The returned AST `tree` can be output via `astor.to_source()`:
middle_repairer = Repairer(middle_debugger) tree, fitness = middle_repairer.repair() print(astor.to_source(tree), fitness)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Here are the classes defined in this chapter. A `Repairer` repairs a program, using a `StatementMutator` and a `CrossoverOperator` to evolve a population of candidates.
# ignore from ClassDiagram import display_class_hierarchy # ignore display_class_hierarchy([Repairer, ConditionMutator, CrossoverOperator], abstract_classes=[ NodeVisitor, NodeTransformer ], p...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Lessons Learned* Automated repair based on genetic optimization uses five ingredients: 1. A _test suite_ to determine passing and failing tests 2. _Defect localization_ (typically obtained from [statistical debugging](StatisticalDebugger.ipynb) with the test suite) to determine potential locations to be fixed ...
from Assertions import square_root # minor dependency with ExpectError(): square_root_of_zero = square_root(0)
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
Can your `ValueMutator` automatically fix this failure? **Solution.** Your solution will be effective if it also includes named constants such as `None`.
import math def square_root_fixed(x): # type: ignore assert x >= 0 # precondition approx = 0 # <-- FIX: Change `None` to 0 guess = x / 2 while approx != guess: approx = guess guess = (approx + x / approx) / 2 assert math.isclose(approx * approx, x) return approx square_root_...
_____no_output_____
MIT
notebooks/Repairer.ipynb
bjrnmath/debuggingbook
BLERSSI Seldon serving Clone Cisco Kubeflow Starter pack repository
BRANCH_NAME="master" #Provide git branch name "master" or "dev" ! git clone -b $BRANCH_NAME https://github.com/CiscoAI/cisco-kubeflow-starter-pack.git
Cloning into 'cisco-kubeflow-starter-pack'... remote: Enumerating objects: 63, done. remote: Counting objects: 100% (63/63), done. remote: Compressing objects: 100% (44/44), done. remote: Total 4630 (delta 16), reused 44 (delta 11), pack-reused 4567 Receiving objects: 100% (4630/4630), 17.61 MiB | 48.72 MiB...
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Install the required packages
! pip install pandas sklearn seldon_core dill alibi==0.3.2 --user
Collecting pandas Downloading pandas-1.0.5-cp36-cp36m-manylinux1_x86_64.whl (10.1 MB)  |████████████████████████████████| 10.1 MB 21.3 MB/s eta 0:00:01 [?25hCollecting sklearn Downloading sklearn-0.0.tar.gz (1.1 kB) Collecting seldon_core Downloading seldon_core-1.2.1-py3-none-any.whl (104 kB)  |██...
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Restart Notebook kernel
from IPython.display import display_html display_html("<script>Jupyter.notebook.kernel.restart()</script>",raw=True)
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Import Libraries
from __future__ import division from __future__ import print_function import tensorflow as tf import pandas as pd import numpy as np import shutil import yaml import random import re import os import dill import logging import requests import json from time import sleep from sklearn.preprocessing import OneHotEncoder ...
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Get NamespaceGet current k8s namespace
def is_running_in_k8s(): return os.path.isdir('/var/run/secrets/kubernetes.io/') def get_current_k8s_namespace(): with open('/var/run/secrets/kubernetes.io/serviceaccount/namespace', 'r') as f: return f.readline() def get_default_target_namespace(): if not is_running_in_k8s(): return 'defa...
anonymous
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Check GPUs availability
gpus = len(tf.config.experimental.list_physical_devices('GPU')) if gpus == 0: print("Model will be trained using CPU") elif gpus >= 0: print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU'))) tf.config.experimental.list_physical_devices('GPU') print("Model will be trained ...
Model will be trained using CPU
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Declare Variables
path="cisco-kubeflow-starter-pack/apps/networking/ble-localization/onprem" BLE_RSSI = pd.read_csv(os.path.join(path, "data/iBeacon_RSSI_Labeled.csv")) #Labeled dataset # Configure model options TF_DATA_DIR = os.getenv("TF_DATA_DIR", "/tmp/data/") TF_MODEL_DIR = os.getenv("TF_MODEL_DIR", "blerssi/") TF_EXPORT_DIR = os....
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
BLERSSI Input Dataset Attribute Informationlocation: The location of receiving RSSIs from ibeacons b3001 to b3013; symbolic values showing the column and row of the location on the map (e.g., A01 stands for column A, row 1).date: Datetime in the format of ‘d-m-yyyy hh:mm:ss’b3001 - b3013: RSSI readings corre...
BLE_RSSI.head(10)
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Definition of Serving Input Receiver Function
feature_columns = make_feature_cols() inputs = {} for feat in feature_columns: inputs[feat.name] = tf.placeholder(shape=[None], dtype=feat.dtype) serving_input_receiver_fn = tf.estimator.export.build_raw_serving_input_receiver_fn(inputs)
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Train and Save BLE RSSI Model
# Feature columns COLUMNS = list(BLE_RSSI.columns) FEATURES = COLUMNS[2:] LABEL = [COLUMNS[0]] b3001 = tf.feature_column.numeric_column(key='b3001',dtype=tf.float64) b3002 = tf.feature_column.numeric_column(key='b3002',dtype=tf.float64) b3003 = tf.feature_column.numeric_column(key='b3003',dtype=tf.float64) b3004 = tf....
INFO:tensorflow:ParameterServerStrategy with compute_devices = ('/device:CPU:0',), variable_device = '/device:CPU:0' Number of devices: 1 INFO:tensorflow:Initializing RunConfig with distribution strategies. INFO:tensorflow:Not using Distribute Coordinator. INFO:tensorflow:Using config: {'_model_dir': 'blerssi/', '_tf_r...
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Define predict function
MODEL_EXPORT_PATH= os.path.join(TF_MODEL_DIR, "export", TF_EXPORT_DIR) def predict(request): """ Define custom predict function to be used by local prediction and explainer. Set anchor_tabular predict function so it always returns predicted class """ # Get model exporter path for dir in os.lis...
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Initialize and fitTo initialize the explainer, we provide a predict function, a list with the feature names to make the anchors easy to understand.
feature_cols=["b3001", "b3002", "b3003", "b3004", "b3005", "b3006", "b3007", "b3008", "b3009", "b3010", "b3011", "b3012", "b3013"] explainer = AnchorTabular(predict, feature_cols)
WARNING:tensorflow:From <ipython-input-8-69054218b064>:31: load (from tensorflow.python.saved_model.loader_impl) is deprecated and will be removed in a future version. Instructions for updating: This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.loader.load or tf.compa...
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Discretize the ordinal features into quartiles. disc_perc is a list with percentiles used for binning
explainer.fit(x1, disc_perc=(25, 50, 75))
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Save Explainer fileSave explainer file with .dill extension. It will be used when creating the InferenceService
EXPLAINER_PATH="explainer" if not os.path.exists(EXPLAINER_PATH): os.mkdir(EXPLAINER_PATH) with open("%s/explainer.dill"%EXPLAINER_PATH, 'wb') as f: dill.dump(explainer,f)
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Create a gatewayCreate a gateway called kubeflow-gateway in namespace anonymous.
gateway=f"""apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: kubeflow-gateway namespace: {namespace} spec: selector: istio: ingressgateway servers: - hosts: - '*' port: name: http number: 80 protocol: HTTP """ gateway_spec=yaml.safe_load(gateway) custom_api....
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Adding a new inference server The list of available inference servers in Seldon Core is maintained in the **seldon-config** configmap, which lives in the same namespace as your Seldon Core operator. In particular, the **predictor_servers** key holds the JSON config for each inference server.[Refer to for more informat...
api_client.patch_namespaced_config_map(name="seldon-config", namespace="kubeflow",pretty=True, body={"data":{"predictor_servers":'{"MLFLOW_SERVER":{"grpc":{"defaultImageVersion":"1.2.1","image":"seldonio/mlflowserver_grpc"},"rest":{"defaultImageVersion":"1.2.1","image":"seldonio/mlflowserver_rest"}},"SKLEARN_SERVER":{"...
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Seldon Serving DeploymentCreate an **SeldonDeployment** with a blerssi model
pvcname = !(echo $HOSTNAME | sed 's/.\{2\}$//') pvc = "workspace-"+pvcname[0] seldon_deploy=f"""apiVersion: machinelearning.seldon.io/v1alpha2 kind: SeldonDeployment metadata: name: blerssi namespace: {namespace} spec: name: blerssi predictors: - graph: children: [] implementation: CUSTOM_INFEREN...
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Wait for state to become available
status=False while True: seldon_status=custom_api.get_namespaced_custom_object_status(group="machinelearning.seldon.io", version="v1alpha2", namespace=namespace, plural="seldondeployments", name=seldon_deploy_spec["metadata"]["name"]) if seldon_status["status"]["state"] == "Available": status=True ...
Status: Creating Status: Creating Status: Available
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Run a Prediction
CLUSTER='ucs' #where your cluster running 'gcp' or 'ucs' %%bash -s "$CLUSTER" --out NODE_IP if [ $1 = "ucs" ] then echo "$(kubectl get node -o=jsonpath='{.items[0].status.addresses[0].address}')" else echo "$(kubectl get node -o=jsonpath='{.items[0].status.addresses[1].address}')" fi %%bash --out INGRESS_PORT I...
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Data for prediction
df_full = pd.read_csv(os.path.join(path,'data/iBeacon_RSSI_Unlabeled_truncated.csv')) #Labeled dataset # Input Data Preprocessing df_full = df_full.drop(['date'],axis = 1) df_full = df_full.drop(['location'],axis = 1) df_full[FEATURES] = (df_full[FEATURES])/(-200) input_data=df_full.to_numpy()[:1] input_data headers...
Probability: 0.6692667603492737 Class-id: 14
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Prediction of the model and explain
explain(input_data)
Anchor: b3009 <= 1.00 AND 0.40 < b3004 <= 1.00 AND 0.39 < b3002 <= 1.00 AND b3012 <= 1.00 AND b3011 <= 1.00 AND b3013 <= 1.00 AND b3006 <= 1.00 AND b3003 <= 1.00 AND b3010 <= 1.00 AND b3005 <= 1.00 AND b3001 <= 1.00 AND b3007 <= 1.00 AND b3008 <= 1.00 Coverage: 0.48
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Clean Up Delete a gateway
custom_api.delete_namespaced_custom_object(group="networking.istio.io", version="v1alpha3", namespace=namespace, plural="gateways", name=gateway_spec["metadata"]["name"],body=k8s_client.V1DeleteOptions())
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Delete Seldon Serving Deployment
custom_api.delete_namespaced_custom_object(group="machinelearning.seldon.io", version="v1alpha2", namespace=namespace, plural="seldondeployments", name=seldon_deploy_spec["metadata"]["name"], body=k8s_client.V1DeleteOptions())
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
Delete model and explainer folders from notebook
!rm -rf $EXPLAINER_PATH !rm -rf $TF_MODEL_DIR
_____no_output_____
Apache-2.0
apps/networking/ble-localization/onprem/seldon/blerssi-seldon.ipynb
Karthik-Git-Sudo786/cisco-kubeflow-starter-pack
MobileCoin Example WalletThis is an example python client that interacts with `mobilecoind` to manage a MobileCoin wallet.You must start the `mobilecoind` daemon in order to run a wallet. See the mobilecoind README for more information.To run this notebook, make sure you have the requirements installed, and that you h...
from mobilecoin import Client
_____no_output_____
Apache-2.0
mobilecoind/clients/python/jupyter/wallet.ipynb
MCrank/mobilecoin
Start the Mob ClientThe client talks to your local mobilecoind. See the mobilecoind/README.md for information on how to set it up.
client = Client("localhost:4444", ssl=False)
_____no_output_____
Apache-2.0
mobilecoind/clients/python/jupyter/wallet.ipynb
MCrank/mobilecoin
Input Root Entropy for AccountNote: The root entropy is sensitive material. It is used as the seed to create your account keys. Anyone with your root entropy can steal your MobileCoin.
entropy = "4ec2c081e764f4189afba528956c05804a448f55f24cc3d04c9ef7e807a93bcd" credentials_response = client.get_account_key(bytes.fromhex(entropy))
_____no_output_____
Apache-2.0
mobilecoind/clients/python/jupyter/wallet.ipynb
MCrank/mobilecoin
Monitor your AccountMonitoring an account means that mobilecoind will persist the transactions that belong to you to a local database. This allows you to retrieve your funds and calculate your balance, as well as to construct and submit transactions.Note: MobileCoin uses accounts and subaddresses for managing funds. Y...
monitor_id_response = client.add_monitor(credentials_response.account_key)
_____no_output_____
Apache-2.0
mobilecoind/clients/python/jupyter/wallet.ipynb
MCrank/mobilecoin
Check BalanceYou will need to provide a subaddress index. Most people will only use one subaddress, and can default to 0. Exchanges or users who want to generate lots of new public addresses may use multiple subaddresses.
subaddress_index = 0 client.get_balance(monitor_id_response.monitor_id, subaddress_index)
_____no_output_____
Apache-2.0
mobilecoind/clients/python/jupyter/wallet.ipynb
MCrank/mobilecoin
Send a TransactionMobileCoin uses "request codes" to wrap public addresses. See below for how to generate request codes.
address_code = "2nTy8m2VE5UMtfqRf12gEjZmFHKNTDEtNufQZNvE713ytYvdu2kqpbcncHJUSLwmgTCkB56Li9fsGwJF9LRYEQvoQCDzqVQEJETDNQKLzqHCzd" target_address_response = client.parse_request_code(address_code) # Construct the transaction txo_list_response = client.get_unspent_tx_output_list(monitor_id_response.monitor_id, subaddress_...
_____no_output_____
Apache-2.0
mobilecoind/clients/python/jupyter/wallet.ipynb
MCrank/mobilecoin
Public Address (Request Code)
public_address_response = client.get_public_address(monitor_id_response.monitor_id, subaddress_index) request_code_response = client.create_request_code(public_address_response.public_address) print(f"Request code = {request_code_response}")
_____no_output_____
Apache-2.0
mobilecoind/clients/python/jupyter/wallet.ipynb
MCrank/mobilecoin
Show me the first lines of the original file
df = pd.read_excel('/tmp/gonzalo_test/aseg.xls') df.head()
_____no_output_____
MIT
notebooks/Miscellaneous/Reshaping an Excel table.ipynb
xgrg/alfa
Show me the region names containing 'Vent' or 'WM' or 'Hippo'
names = set([each for each in df['StructName'].tolist() \ if 'WM' in each or 'Vent' in each or 'Hippo' in each]) names
_____no_output_____
MIT
notebooks/Miscellaneous/Reshaping an Excel table.ipynb
xgrg/alfa
Reshape the table and show me the first lines
df = pd.DataFrame(df[df['StructName'].isin(names)], columns=['subject', 'StructName', 'Volume_mm3']) df = df.pivot(index='subject', columns='StructName', values='Volume_mm3') df.head()
_____no_output_____
MIT
notebooks/Miscellaneous/Reshaping an Excel table.ipynb
xgrg/alfa
Save it and success !
df.to_excel('/tmp/gonzalo_test/aseg_pivot.xls') from IPython.display import Image Image(url='http://s2.quickmeme.com/img/c3/c37a6cc5f88867e5387b8787aaf67afc350b3f37f357ed0a3088241488063bce.jpg')
_____no_output_____
MIT
notebooks/Miscellaneous/Reshaping an Excel table.ipynb
xgrg/alfa
The effect of temperature and reaction time affects the %yield. Develop a model for %yield in terms of temperature and time
import pandas as mypanda import numpy as np from scipy import stats as mystats import matplotlib.pyplot as myplot from pandas.plotting import scatter_matrix from statsmodels.formula.api import ols as myols from statsmodels.stats.anova import anova_lm myData=mypanda.read_csv('datasets/Mult_Reg_Yield.csv') myData tmp=myD...
_____no_output_____
Apache-2.0
Regression_Analysis_Chemical_Process.ipynb
mohan-mj/Regression_Analysis
check for relationship now
scatter_matrix(myData) myplot.show()
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead. """Entry point for launching an IPython kernel.
Apache-2.0
Regression_Analysis_Chemical_Process.ipynb
mohan-mj/Regression_Analysis
correlation between xs and y should be high
np.corrcoef(tmp,yld) np.corrcoef(time,yld) np.corrcoef(time,tmp) mymodel=myols("yld ~ time + tmp",myData) mymodel=mymodel.fit() mymodel.summary()
C:\ProgramData\Anaconda3\lib\site-packages\scipy\stats\stats.py:1334: UserWarning: kurtosistest only valid for n>=20 ... continuing anyway, n=16 "anyway, n=%i" % int(n))
Apache-2.0
Regression_Analysis_Chemical_Process.ipynb
mohan-mj/Regression_Analysis
check p value ==> only time is related to yield
mymodel=myols("yld ~ time ",myData).fit() mymodel.summary() pred=mymodel.predict() res=yld-pred res #print(yld, res) myplot.scatter(yld,pred) myplot.show() mystats.probplot(res,plot=myplot) myplot.show() mystats.normaltest(res)
C:\ProgramData\Anaconda3\lib\site-packages\scipy\stats\stats.py:1334: UserWarning: kurtosistest only valid for n>=20 ... continuing anyway, n=16 "anyway, n=%i" % int(n))
Apache-2.0
Regression_Analysis_Chemical_Process.ipynb
mohan-mj/Regression_Analysis
Implies it is normal
myplot.scatter(time,res) myplot.show() myplot.scatter(pred,res) myplot.show()
_____no_output_____
Apache-2.0
Regression_Analysis_Chemical_Process.ipynb
mohan-mj/Regression_Analysis
**Análise de Dados com Python e Pandas**
# Monta o drive no ambiente virtual permitindo acesso aos arquivos do drive from google.colab import drive drive.mount('/content/drive') # Permite escolher um arquivo da máquina para upload no colab from google.colab import files arq = files.upload() from google.colab import drive drive.mount('/content/drive')
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
*Importando a biblioteca Pandas*
#importando a biblioteca Pandas import pandas as pd
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
*Lendo arquivos*
#Lendo CSV df = pd.read_csv("/content/drive/MyDrive/Datasets/Gapminder.csv", error_bad_lines=False, sep=";") #Visualizando as 5 primeiras linhas df.head()
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
*Renomeando Colunas*
df = df.rename(columns={'country':'Country', 'continent':'Continent', 'year':'Year', 'lifeExp':'LifeExp', 'pop':'Population', 'gdpPercap':'PIB'}) df.head()
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
*Trabalhando com Linhas e Colunas do arquivo*
#Quantidade de linhas e colunas dentro do arquivo df.shape #Nome das colunas df.columns
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
#Tipo de dado em ccada coluna df.dtypes #Últimas cindo linhas por padrao do arquivo (df.tail(10) → Últimas 10 linhas...) df.tail() #Média entre os dados das respectivas linhas e colunas df.describe()
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
*Trabalhando com Filtros*
df['Continent'].unique() Oceania = df.loc[df['Continent'] == 'Oceania'] Oceania.head() Oceania['Continent'].unique() df.groupby('Continent')['Country'].nunique() df.groupby('Year')['LifeExp'].mean() df['PIB'].mean() df['PIB'].sum()
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
**Trabalhando com Planilhas de Excel** *Leitura dos Arquivos*
df1 = pd.read_excel("/content/drive/MyDrive/Datasets/Aracaju.xlsx") df2 = pd.read_excel("/content/drive/MyDrive/Datasets/Fortaleza.xlsx") df3 = pd.read_excel("/content/drive/MyDrive/Datasets/Natal.xlsx") df4 = pd.read_excel("/content/drive/MyDrive/Datasets/Recife.xlsx") df5 = pd.read_excel("/content/drive/MyDrive/Datas...
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
***Tratando valores faltantes***
#Consultando linhas com valores faltantes df.isnull().sum() #Apagando as linhas com valores nulos df.dropna(inplace=True) #Apagando as linhas com valores nulos com base apenas em 1 coluna df.dropna(subset=['Vendas'], inplace=True) #Removendo linhas que estejam com valores faltantes em todas as colunas df.dropna(how='al...
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
***Criando novas colunas***
#Criando a coluna de receita df['Receita'] = df['Vendas'].mul(df['Qtde']) df.head() df.tail() df['Receita/Venda'] = df['Receita'] / df['Vendas'] df.head() #Retornando maior receita df['Receita'].max() #Retornando a menor receita df['Receita'].min() #nlargest df.nlargest(3,'Receita') #nsmallest df.nsmallest(3, 'Receita'...
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
***Trabalhando com datas***
#Transfomando a coluna de dataa em tipo inteiro df['Data'] = df['Data'].astype('int64') #Verificando o tipo de dado de cada coluna df.dtypes #Transformando a coluna de Data em Data df['Data'] = pd.to_datetime(df['Data']) df.dtypes #Agrupamento por ano df.groupby(df['Data'].dt.year)['Receita'].sum() #Criado uma nova col...
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
**Visualizacao de Dados**
df['LojaID'].value_counts(ascending=False)
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
***Gráficos***
#Gráfico de barras df['LojaID'].value_counts(ascending=False).plot.bar(); #Gráfico de barras horizontais df['LojaID'].value_counts().plot.barh(); #Gráfco de barras horizonatal df['LojaID'].value_counts(ascending=True).plot.barh(); #Gráfico de Pizza df.groupby(df['Data'].dt.year)['Receita'].sum().plot.pie(); #Total de v...
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
**Análise Exploratória**
plt.style.use('seaborn') #Upload de arquivo from google.colab import files arq = files.upload() #Criando nosso DataFrame df = pd.read_excel("/content/drive/MyDrive/Datasets/AdventureWorks.xlsx") df.head() #Quantidade de linhas e colunas df.shape #Verificando os tipos de dados df.dtypes #Qual a Receita total? df['Valor ...
_____no_output_____
MIT
pandasProjectCognizant/project_python_Pandas.ipynb
luizpavanello/cognizant_bootcamp_DIO
Aerospike Java Client – Advanced Collection Data Types*Last updated: June 22, 2021*The goal of this tutorial is to highlight the power of working with [collection data types (CDTs)]("https://docs.aerospike.com/docs/guide/cdt.html") in Aerospike. It covers the following topics:1. Setting [contexts (CTXs)]("https://docs...
import io.github.spencerpark.ijava.IJava; import io.github.spencerpark.jupyter.kernel.magic.common.Shell; IJava.getKernelInstance().getMagics().registerMagics(Shell.class);
_____no_output_____
MIT
notebooks/java/java-advanced_collection_data_types.ipynb
markprincely/interactive-notebooks
Start AerospikeEnsure Aerospike Database is running locally.
%sh asd
_____no_output_____
MIT
notebooks/java/java-advanced_collection_data_types.ipynb
markprincely/interactive-notebooks
Download the Aerospike Java ClientAsk Maven to download and install the project object model (POM) of the Aerospike Java Client.
%%loadFromPOM <dependencies> <dependency> <groupId>com.aerospike</groupId> <artifactId>aerospike-client</artifactId> <version>5.0.0</version> </dependency> </dependencies>
_____no_output_____
MIT
notebooks/java/java-advanced_collection_data_types.ipynb
markprincely/interactive-notebooks
Start the Aerospike Java Client and ConnectCreate an instance of the Aerospike Java Client, and connect to the demo cluster.The default cluster location for the Docker container is *localhost* port *3000*. If your cluster is not running on your local machine, modify *localhost* and *3000* to the values for your Aerosp...
import com.aerospike.client.AerospikeClient; AerospikeClient client = new AerospikeClient("localhost", 3000); System.out.println("Initialized the client and connected to the cluster.");
Initialized the client and connected to the cluster.
MIT
notebooks/java/java-advanced_collection_data_types.ipynb
markprincely/interactive-notebooks
Create CDT Data, Put into Aerospike, and Print It
import com.aerospike.client.Key; import com.aerospike.client.Bin; import com.aerospike.client.policy.ClientPolicy; import com.aerospike.client.Record; import com.aerospike.client.Operation; import com.aerospike.client.Value; import com.aerospike.client.cdt.ListOperation; import com.aerospike.client.cdt.ListPolicy; impo...
listwhalebin: [[1420, beluga whale, Beaufort Sea, Bering Sea], [13988, gray whale, Baja California, Chukchi Sea], [1278, north pacific right whale, Japan, Sea of Okhotsk], [5100, humpback whale, Columbia, Antarctic Peninsula], [3100, southern hemisphere blue whale, Corcovado Gulf, The Galapagos]] mapobsbin: {13456={la...
MIT
notebooks/java/java-advanced_collection_data_types.ipynb
markprincely/interactive-notebooks
Using Contexts (CTXs) to work with Nested CDTsWhat are Nested CDTs and CTXs? What is a Nested CDT?The primary use case of Key-Value Stores, like Aerospike Database, is to store document-oriented data, like a JSON map. As document-oriented data grows organically, it is common for one CDT (list or map) to contain anoth...
import com.aerospike.client.cdt.CTX; import com.aerospike.client.cdt.MapReturnType; Integer lookupMapKey = 14567; String latKeyName = "lat"; Record whaleSightings = client.operate(client.writePolicyDefault, whaleKey, MapOperation.getByKey(mapObsBinName, Value.get(latKeyName), MapReturnType.VALUE, CTX.mapKey(Valu...
mapobsbin: {13456={lat=-25, long=-50}, 14567={lat=35, long=30}, 12345={lat=-85, long=-130}} The lat of sighting at timestamp 14567: 35
MIT
notebooks/java/java-advanced_collection_data_types.ipynb
markprincely/interactive-notebooks
Drill down into a List or MapHere are the options to drill down into a CDT.Drilling down to a CTX in a List:* `listIndex`: Lookup list by index offset.* `listRank`: Lookup list by rank.* `listValue`: Lookup list by value.Drilling down to a CTX in a Map: * `mapIndex`: Lookup map by index offset.* `mapRank`: Lookup map ...
import com.aerospike.client.cdt.ListReturnType; // CDT Drilldown Values Integer drilldownIndex = 2; Integer drilldownRank = 1; Value listDrilldownValue = Value.get(whaleMigration1); Value mapDrilldownValue = Value.get(mapCoords0); // Variables to access parts of the selected CDT. Integer getIndex = 1; Record theRe...
The whale migration list is: [[1420, beluga whale, Beaufort Sea, Bering Sea], [13988, gray whale, Baja California, Chukchi Sea], [1278, north pacific right whale, Japan, Sea of Okhotsk], [5100, humpback whale, Columbia, Antarctic Peninsula], [3100, southern hemisphere blue whale, Corcovado Gulf, The Galapagos]] The wh...
MIT
notebooks/java/java-advanced_collection_data_types.ipynb
markprincely/interactive-notebooks